(function () {
    // 全局注册Liquid渲染测试更新
    var Liquid = window.liquidjs.Liquid;
    window.engine = new Liquid({
        extname: ".html",
        cache: true,
        globals: {
            theme_config: window.themeConfig || {}
        }
    });
    window.engine.registerFilter("current_countrys", (item, key) => {
        if (!item) {
            return `${oemcart_imgcdn}/statics/country/flag/default.png`;
        } else {
            const file = oemcart_countrys[item].country_code_2.toLowerCase();
            return `${oemcart_imgcdn}/statics/country/flag/${file}.png`;
        }
    });

    window.engine.registerFilter("money", (item, key,key2,key3) => {
        return formatMoney(parseFloat(item || 0), key || window.oemcart_currency,key2 || "",key3 ||"");
    });

    window.engine.registerFilter("public_asset_abs_url", (item, key) => {
        return oemcart_imgcdn+"/uploads/0/theme/default/assets/" + item;
    });

    window.engine.registerFilter("lazy_img_url", (item, key) => {
        if(item){
            switch (key) {
                case "banner":
                    return oemcart_imgcdn+"/uploads/0/theme/default/assets/banner_loading.png";
                default:
                    return oemcart_imgcdn+"/uploads/0/theme/default/assets/empty_loading.png";
            }
            
        }else{
            switch (key) {
                case "banner":
                    return oemcart_imgcdn+"/uploads/0/theme/default/assets/banner@2x.png";
                default:
                    return oemcart_imgcdn+"/uploads/0/theme/default/assets/empty.png";
            }
        }
    });

    function Moi(params) {
        //页面数据
        this.pageStorage = {};

        //事件
        this.event = {};

        // //loading重复点击
        // this.loadShake = {};

        //添加购物车时间
        // addToCart:[]

        this.ProductPictureShake = true;
        this.ProductShake = true;

        this.globalpopupLayer;
    }

    Moi.prototype.isEvent = function (name) {
        if (!this.event[name]) {
            return false
        }
        return true
    }

    Moi.prototype.addEvent = function (name, fun, isDefault) {
        const self = this;
        if (!this.event[name]) {
            this.event[name] = {
                isExecute: true,
                default: false,
                defaultFunction: null,
                params: {},
                preventDefault(event) {
                    //阻止默认
                    self.event[name].default = false;
                },
                stopPropagation() {
                    //阻止冒泡
                    self.event[name].isExecute = false;
                },
                results:[],
                fun: []
            };
        }

        if (isDefault && fun) {
            //    = fun.call(this, self.event);
            this.event[name].default = true;
            this.event[name].defaultFunction = fun; //  .bind(this, self.event)
            return;
        }

        this.event[name].fun.push(fun);
    };

    Moi.prototype.onEvent = function (name, params) {
        const event = this.event[name];
        if (!event || event === undefined) {
            return params ? { params: params } : false;
        }
        event.results = [];
        event.params = params;
        let eventLength = 0;

        if (event.fun && event.fun.length) {
            while (event.isExecute) {
                try {
                    var retData = event.fun[eventLength].call(this, event);
                } catch (error) {
                    console.log(error)
                }
                if(typeof(retData) !== "undefined"){
                    event.results.push(retData);
                }
                eventLength++;
                if (eventLength === event.fun.length) {
                    event.isExecute = false;
                }
                // if(typeof(retData) !== "undefined"){
                //     return retData
                // }else{
                //     eventLength++;
                //     if (eventLength === event.fun.length) {
                //         event.isExecute = false;
                //     }
                // }

            }
        }

        if (event.default) {
            event.defaultFunction.call(this, event);
        }

        //重置
        event.isExecute = true;

        return event;
    };

    // 移除事件
    Moi.prototype.removeEvent = function (name) {
        // this.event[name] = undefined;
    };

    Moi.prototype.removeEventListener = function(name, fun){
        if(this.event[name]){
            const index = this.event[name].fun.findIndex(itemFun=>itemFun == fun);
            if(index != -1){
                this.event[name].fun.splice(index,1)
            }
        }
    }

    // 移除所有事件
    Moi.prototype.removeAllEvent = function (name) {
        this.event[name] = undefined;
    };

    // 表单方法
    Moi.prototype.form = function (id, rule) {
        //验证规则
        const copyRule = rule;

        // 获取fom接单
        const formNodes = $(id);

        //表单子元素
        const items = formNodes.find(`.mo-form-item`);

        //回调事件
        const callbackFu = {
            //获取input信息
            getInputValue: function (inputs, index) {
                const values = [];
                if (inputs.length) {
                    for (let i = 0; i < inputs.length; i++) {
                        const inputNode = inputs[i];

                        //绑定焦点事件
                        inputNode.addEventListener("focus", function (params) {
                            callbackFu.hideError(index);
                        });

                        values.push({ value: inputNode.value.trim(), index: index });
                    }
                }
                return values;
            },
            //获取所有value
            allValue: function () {
                const itemValues = {};
                for (let i = 0; i < items.length; i++) {
                    const itemNode = $(items[i]);
                    if (itemNode.attr("name")) {
                        // || `key_${i}`
                        const key = itemNode.attr("name");
                        var input = itemNode.find("input");
                        var textarea = itemNode.find("textarea");
                        itemValues[key] = callbackFu.getInputValue(input.length ? input : textarea, i);
                    }
                }
                return itemValues;
            },

            //隐藏错误信息
            hideError: function (index) {
                const itemNode = $(items[index]);
                if (itemNode.hasClass("form-show-error")) {
                    itemNode.removeClass("form-show-error");
                }
            },

            //显示错误
            showError: function (index, message) {
                const activeClas = "form-show-error";
                const itemNode = $(items[index]);
                const errorNode = itemNode.children(".mo-form-item-error");
                //初次错误追加元素
                if (!errorNode.length) {
                    return itemNode.addClass(activeClas).append(`<div class="mo-form-item-error">${message}</div>`);
                }

                //二次错误设置class
                if (!itemNode.hasClass(activeClas)) {
                    console.log("二次错误");
                    errorNode.html(message);
                    return itemNode.addClass(activeClas);
                }
            },

            //验证规则
            verifyRule(rules, value, index) {
                let returnStr = true;
                for (let i = 0; i < rules.length; i++) {
                    const rule = rules[i];

                    //验证必填

                    if (rule.required && !value.trim()) {
                        callbackFu.showError(index, rule.message);
                        returnStr = false;
                        return;
                    }

                    //是否有自定义验证
                    if (rule.validator) {
                        rule.validator(value, rules, function (msg) {
                            if (msg) {
                                callbackFu.showError(index, msg);
                                returnStr = false;
                            }
                        });
                    }
                }

                return returnStr;
            },

            //验证所有
            allVerify: function () {
                let status = true;

                const allValues = callbackFu.allValue();
                const keys = Object.keys(allValues);
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];

                    const value = allValues[key].map((el) => el.value).toString();
                    const index = allValues[key].length && allValues[key][0].index;
                    //验证数据
                    if (copyRule[key] && !callbackFu.verifyRule(copyRule[key], value, index)) {
                        status = false;
                    }
                }

                return status;
            },

            //验证
            verify: function (name) {
                const allValues = callbackFu.allValue();

                const keys = Object.keys(allValues);

                const key = name;

                const value = allValues[key].map((el) => el.value).toString();
                // const value = allValues[key].toString();

                //验证数据

                if (copyRule[key] && !callbackFu.verifyRule(copyRule[key], value, keys.indexOf(name))) {
                    return false;
                }

                return true;
            }
        };

        return callbackFu;
    };

    //form value 数组变字符串
    Moi.prototype.paramsValueString = function (obj) {
        var keys = Object.keys(obj);
        keys.forEach((key) => {
            obj[key] = obj[key].map((el) => el.value).toString();
        });
        return obj;
    };

    //显示加载框
    Moi.prototype.nodeShowLoading = function (dom, str) {
        var selfDom = $(dom);
        var className = "mo-loading-warp";
        var old = selfDom.html();
        var style = "";
        if (str) {
            className = className + " " + str;
        }
        selfDom.addClass(className);
        if (str && str.indexOf("#") > -1) {
            style = `style="border-color:${str}; border-bottom-color: transparent;"`;
        }
        selfDom.html(`<div class="mo-loading" ${style}></div>`);
        return {
            //回调关闭加载样式
            close: function () {
                selfDom.removeClass(className);
                selfDom.html(old);
            }
        };
    };

    // //ajax
    // Moi.prototype.ajax = function (option) {
    //     $.ajax({
    //         ...option
    //     });
    // };

    //设置cookie
    //这是有设定过期时间的使用示例：
    //s20是代表20秒
    //h是指小时，如12小时则是：h12
    //d是天数，30天则：d30
    Moi.prototype.setCookie = function (name, value, time, path, domain) {
        var strsec = getsec(time);
        var exp = new Date();
        exp.setTime(exp.getTime() + strsec * 1);
        document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + ";path=" + (path || "/") + ";domain=" + (domain || "") + ";SameSite=None; Secure";
    };

    function getsec(str) {
        var str1 = str.substring(1, str.length) * 1;
        var str2 = str.substring(0, 1);
        if (str2 == "s") {
            return str1 * 1000;
        } else if (str2 == "h") {
            return str1 * 60 * 60 * 1000;
        } else if (str2 == "d") {
            return str1 * 24 * 60 * 60 * 1000;
        }
    }

    //删除cookie
    Moi.prototype.delCookie = function (name, path, domain) {
        var date = new Date();
        date.setTime(date.getTime() +(-1*24*60*60*1000));
        document.cookie = name + "=a; expires=" + date.toGMTString() + ";path=" + (path || "/") + ";domain=" + (domain || "");
        // var d = new Date();
        // d.setTime(d.getTime() + -1 * 24 * 60 * 60 * 1000);
        // var expires = "expires=" + d.toUTCString();
        // var path_ = "path=" + path || "/",
        //     domain_ = domain ? "domain=" + domain + ";" : "";
        // document.cookie = cname + "=''; " + domain_ + expires + "; " + path_;
    };

    //获取cookie
    Moi.prototype.getCookie = function (name) {
        var arr,
            reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if ((arr = document.cookie.match(reg))) return decodeURIComponent(arr[2]);
        else return null;
    };

    //获取链接参数
    Moi.prototype.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); //匹配目标参数
        if (r != null) {
            r[2] = r[2].replace("+", " ");
            return decodeURIComponent(r[2]);
        }
        return ""; //返回参数值
    };

    //修改链接参数
    Moi.prototype.changeURLArg = function (url, arg, arg_val) {
        var pattern = arg + "=([^&]*)";
        var replaceText = arg + "=" + encodeURIComponent(arg_val);
        if (url.match(pattern)) {
            var tmp = "/(" + arg + "=)([^&]*)/gi";
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match("[?]")) {
                return url + "&" + replaceText;
            } else {
                return url + "?" + replaceText;
            }
        }
    };

    /**
     * @description: 设置链接参数
     * @param {*} url 拦截
     * @param {*} params get参数
     * @return {*} url
     */
    Moi.prototype.setUrlParams = function (url, params) {
        let newURL = url;
        const paramsKey = Object.keys(params);
        paramsKey.forEach((key) => {
            // if (params[key] !== "") {
            newURL = this.changeURLArg(newURL, key, params[key]);
            // }
        });
        return newURL;
    };

    //修改链接参数
    Moi.prototype.addURLParam = function (url, key, value) {
        var replaceText = key + "=" + value;
        if (url.match("[?]")) {
            return url + "&" + replaceText;
        } else {
            return url + "?" + replaceText;
        }
    };

    //删除链接参数
    Moi.prototype.removeParam = function (key,sourceURL) {
        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = sourceURL.indexOf("?") !== -1 ? sourceURL.split("?")[1] : "";
        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }

            if(params_arr.length){
                rtn = rtn + "?" + params_arr.join("&");
            }
            return rtn

        }
        return rtn;
    };
   

    Moi.prototype.isMobile = function () {
        if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
            //移动端
            return true;
        }
        if (document.body.clientWidth < 750) {
            return true;
        }
        return false;
    };

    //提示框
    Moi.prototype.alert = function (options) {
        const template = `<div class="mo-confirm"><div class="mo-confirm-body"><div class="mo-title">${options.title}</div><div class="mo-handle"><div class="mo-handle-btn mo-handle-ok">${lang.general.yes}</div></div></div></div>`;
        const temp = $(template);
        // const closeNodes = temp.find(".mo-handle-close")[0];
        const okNodes = temp.find(".mo-handle-ok")[0];

        //关闭事件
        function close() {
            // closeNodes.removeEventListener("click", close, false);
            okNodes.removeEventListener("ok", ok, false);
            temp.remove();
        }

        //确定事件
        function ok() {
            options.ok && options.ok();
            close();
        }

        // closeNodes.addEventListener("click", close, false);
        okNodes.addEventListener("click", ok, false);

        $("body").append(temp);
    };

    //轻提示框
    Moi.prototype.alertInfo = function ({ content = "", timer = 2000, type = "info", placement = "center", onClose }) {
        const alertTypesMap = {
            info: "",
            success:
                '<svg t="1658471413522" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17451" width="200" height="200"><path d="M512 1024C229.180952 1024 0 794.819048 0 512S229.180952 0 512 0s512 229.180952 512 512-229.180952 512-512 512z m0-975.238095C256 48.761905 48.761905 256 48.761905 512s207.238095 463.238095 463.238095 463.238095 463.238095-207.238095 463.238095-463.238095S768 48.761905 512 48.761905z" fill="#25AA53" p-id="17452"></path><path d="M763.12381 329.142857c-9.752381-9.752381-24.380952-9.752381-34.133334 0l-292.571428 292.571429-134.095238-134.095238c-9.752381-7.314286-24.380952-7.314286-31.695239 2.438095-9.752381 7.314286-9.752381 21.942857-2.438095 31.695238l153.6 153.6c9.752381 7.314286 24.380952 7.314286 31.695238-2.438095l2.438096-2.438096c2.438095 0 4.87619-2.438095 4.87619-4.87619l302.32381-302.32381c9.752381-9.752381 9.752381-24.380952 0-34.133333z" fill="#25AA53" p-id="17453"></path></svg>',
            warn: '<svg t="1658471442639" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17602" width="200" height="200"><path d="M512 1024C229.180952 1024 0 794.819048 0 512S229.180952 0 512 0s512 229.180952 512 512-229.180952 512-512 512z m0-975.238095C256 48.761905 48.761905 256 48.761905 512s207.238095 463.238095 463.238095 463.238095 463.238095-207.238095 463.238095-463.238095S768 48.761905 512 48.761905z" fill="#E88C4E" p-id="17603"></path><path d="M512.609524 268.190476c14.628571 0 24.380952 9.752381 24.380952 24.380953v316.952381c0 14.628571-9.752381 24.380952-24.380952 24.380952s-24.380952-9.752381-24.380953-24.380952V292.571429c0-14.628571 9.752381-24.380952 24.380953-24.380953zM488.228571 731.428571h48.761905v48.761905h-48.761905z" fill="#E88C4E" p-id="17604"></path></svg>',
            danger: '<svg t="1658471452213" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17753" width="200" height="200"><path d="M512 1024C229.180952 1024 0 794.819048 0 512S229.180952 0 512 0s512 229.180952 512 512-229.180952 512-512 512z m0-975.238095C256 48.761905 48.761905 256 48.761905 512s207.238095 463.238095 463.238095 463.238095 463.238095-207.238095 463.238095-463.238095S768 48.761905 512 48.761905z" fill="#DB2739" p-id="17754"></path><path d="M702.171429 668.038095l-153.6-153.6 146.285714-146.285714c9.752381-9.752381 9.752381-24.380952 0-34.133333-9.752381-9.752381-24.380952-9.752381-34.133333 0l-146.285715 146.285714-153.6-153.6c-4.87619-4.87619-17.066667-2.438095-26.819047 7.314286s-12.190476 21.942857-7.314286 26.819047l153.6 153.6-146.285714 146.285715c-9.752381 9.752381-9.752381 24.380952 0 34.133333s24.380952 9.752381 34.133333 0l146.285714-146.285714 153.6 153.6c4.87619 4.87619 17.066667 2.438095 26.819048-7.314286s12.190476-21.942857 7.314286-26.819048z" fill="#DB2739" p-id="17755"></path></svg>'
        };
        const ANIMATION_TIMER = 1000,
            MODAL_ID = `mo-alert-info-model_${Date.now()}`;
        const html = `
               <div class="mo-alert-info-model mo-alert-info-model_${placement}" id="${MODAL_ID}">
                  <div class="mo-alert-info-body" style="animation-duration: ${ANIMATION_TIMER}ms">
                     ${alertTypesMap[type]}
                     <span class="mo-alert-info-content">${content}</span>
                  </div>
               </div>
            `;

        $(".mo-alert-info-model").remove();
        $(document.body).append(html);

        // 关闭
        setTimeout(() => {
            const $alertBody = $(`#${MODAL_ID} .mo-alert-info-body`);
            if (placement === "center") {
                $alertBody.addClass("mo-alert-info_close-center-animation");
            } else {
                $alertBody.addClass("mo-alert-info_close-top-animation");
            }

            setTimeout(() => {
                $(`#${MODAL_ID}`).remove();
                onClose && onClose();
            }, ANIMATION_TIMER - 80 /* 减去80ms，防止出现计时误差 */);
        }, timer + ANIMATION_TIMER);
    };

    // 消息框
    Moi.prototype.message = function (options) {
        const defaultOption = {
            type: "success", // success，error，info
            content: "content",
            onClose: null,
            link: "",
            timer: 2000,
            ...options
        };
        let icon = "";

        switch (defaultOption.type) {
            case "success":
                icon = `<svg t="1641532926783" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9539" width="200" height="200"><path d="M512 25.6a486.5408 486.5408 0 0 0-189.3248 934.592 486.528 486.528 0 0 0 378.6496-896.384A483.328 483.328 0 0 0 512 25.6m0-25.6A512 512 0 1 1 0 512 512 512 0 0 1 512 0z" fill="#29BB9D" p-id="9540"></path><path d="M274.092113 486.674451m9.050966 9.050967l162.917403 162.917402q9.050967 9.050967 0 18.101934l0 0q-9.050967 9.050967-18.101934 0l-162.917402-162.917403q-9.050967-9.050967 0-18.101933l0 0q9.050967-9.050967 18.101933 0Z" fill="#29BB9D" p-id="9541"></path><path d="M775.375724 350.881006m-9.050967 9.050967l-316.783838 316.783838q-9.050967 9.050967-18.101933 0l0.009051 0.009051q-9.050967-9.050967 0-18.101934l316.783838-316.783838q9.050967-9.050967 18.101933 0l-0.009051-0.009051q9.050967 9.050967 0 18.101934Z" fill="#29BB9D" p-id="9542"></path></svg>`;
                break;
            case "error":
                icon = `<svg t="1635319085856" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="29395" width="200" height="200">
                <path d="M512 512m-512 0a512 512 0 1 0 1024 0 512 512 0 1 0-1024 0Z" fill="#EE4550" p-id="29396"></path>
                <path d="M548.266667 512.341333l126.976 127.232a25.642667 25.642667 0 0 1-36.224 36.309334L512 548.650667l-126.976 127.232a25.642667 25.642667 0 0 1-36.224-36.309334l126.976-127.232-126.976-127.232a25.6 25.6 0 0 1 0.128-36.010666 25.6 25.6 0 0 1 36.138667 0l126.933333 126.933333 126.976-127.232a25.642667 25.642667 0 0 1 36.224 36.309333l-126.933333 127.232z" fill="#FFFFFF" p-id="29397"></path>
              </svg>`;
                break;
            case "info":
                icon = `<svg t="1635319120477" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="29528" width="200" height="200">
                <path
                  d="M512 0a512 512 0 1 0 512 512 512 512 0 0 0-512-512z m31.552 757.824a52.096 52.096 0 0 1-35.648 13.696 53.952 53.952 0 0 1-36.544-13.568 47.488 47.488 0 0 1-15.616-37.888 48.832 48.832 0 0 1 15.104-36.352 51.2 51.2 0 0 1 37.056-14.72 50.368 50.368 0 0 1 51.2 51.2 47.872 47.872 0 0 1-15.424 37.696z m128-317.504a156.096 156.096 0 0 1-28.096 37.888q-16.256 15.936-58.432 53.632a238.208 238.208 0 0 0-18.688 18.688 75.904 75.904 0 0 0-10.432 14.72 72.448 72.448 0 0 0-5.312 13.376q-1.856 6.4-5.632 23.488a38.4 38.4 0 0 1-40.768 35.648 41.664 41.664 0 0 1-30.016-11.648 45.76 45.76 0 0 1-12.16-34.624 121.6 121.6 0 0 1 32.576-86.912 543.488 543.488 0 0 1 39.744-37.888q21.952-19.2 32-28.992a99.136 99.136 0 0 0 16.448-21.76 52.544 52.544 0 0 0 6.4-26.048 60.608 60.608 0 0 0-20.416-46.272 74.56 74.56 0 0 0-52.608-18.816 72.768 72.768 0 0 0-55.552 19.2 151.488 151.488 0 0 0-30.208 56.064q-11.648 38.4-44.224 38.4a43.456 43.456 0 0 1-32.384-13.568 41.344 41.344 0 0 1-13.184-29.312 123.776 123.776 0 0 1 20.928-65.984 160.896 160.896 0 0 1 60.992-55.36 192 192 0 0 1 93.632-21.952 199.872 199.872 0 0 1 87.744 18.368 142.272 142.272 0 0 1 58.816 49.856 122.304 122.304 0 0 1 20.736 68.544 105.984 105.984 0 0 1-11.84 51.2z"
                  fill="#333333" p-id="29529"></path>
              </svg>`;
                break;
        }

        const template = `<div class=mo-modal><div class=mo-modal-mask></div><div class=mo-modal-body><div class=mo-modal-warp>${icon} <span class="message-text">${defaultOption.content}</span></div></div></div>`;
        const temp = $(template);
        $("body").append(temp);

        const modelBody = temp.find(".mo-modal-body");
        modelBody.addClass("animated bounceIn");

        setTimeout(() => {
            modelBody.addClass("animated bounceOut"); //取消动画
            setTimeout(function () {
                //关闭弹窗
                temp.remove();
                //是否存在链接跳转
                if (defaultOption.link) {
                    window.location.href = defaultOption.link;
                    return;
                }
                defaultOption.onClose && defaultOption.onClose.call(this, {});
            }, 500);
        }, defaultOption.timer);
    };

    //询问框
    Moi.prototype.confirm = function (options) {
        const defaultOption = {
            title: "content",
            okText: lang.general.yes,
            cancelText: lang.general.no,
            ...options
        };

        const template = `<div class="mo-confirm"><div class="mo-confirm-body"><div class="mo-title">${defaultOption.title}</div><div class="mo-handle"><div class="mo-handle-btn mo-handle-ok">${defaultOption.okText}</div><div class="mo-handle-btn mo-handle-close">${defaultOption.cancelText}</div></div></div></div>`;
        const temp = $(template);
        const closeNodes = temp.find(".mo-handle-close")[0];
        const okNodes = temp.find(".mo-handle-ok")[0];

        //关闭事件
        function close() {
            closeNodes.removeEventListener("click", close, false);
            okNodes.removeEventListener("ok", ok, false);
            temp.find(".mo-confirm-body").addClass("animated bounceOut");
            setTimeout(function () {
                temp.remove();
            }, 500);
        }

        //关闭事件
        function ok() {
            options.ok && options.ok();
            close();
        }

        closeNodes.addEventListener("click", close, false);
        okNodes.addEventListener("click", ok, false);

        $("body").append(temp);

        temp.find(".mo-confirm-body").addClass("animated bounceIn");
    };

    //定位到元素

    Moi.prototype.windowPositionNode = function (id) {
        $("html,body").animate({ scrollTop: $(id).offset().top }, 200);
    };

    //文字提示框
    Moi.prototype.tooltip = function (options) {
        const defaultOption = {
            placement: "left",
            el: "",
            timer: 1000,
            space: 0,
            content: "",
            ...options
        };

        const cssOption = {
            opacity: 1,
            transform: "scale(1)",
            visibility: "visible"
        };

        const template = `<div class="mo-tooltip mo-tooltip-placement-${defaultOption.placement}">
    <div class="mo-tooltip-content">
      <div class="mo-tooltip-arrow"><span class="mo-tooltip-arrow-content"></span></div>
      <div class="mo-tooltip-inner" role="tooltip">${defaultOption.content}</div>
    </div>
  </div>`;
        const temp = $(template);

        const node = $(defaultOption.el);

        const top = node.offset().top;
        const width = node.width();
        const height = node.height();
        const left = node.offset().left;

        //追加页面元素
        $("body").append(temp);

        const tipWidth = temp.innerWidth();
        const tipHeight = temp.innerHeight();

        switch (defaultOption.placement) {
            case "left":
                temp.css({
                    ...cssOption,
                    left: left - tipWidth - defaultOption.space,
                    top: top - Math.floor(height / 2)
                });
                break;
            case "right":
                temp.css({
                    ...cssOption,
                    left: left + width + defaultOption.space,
                    top: top - Math.floor(height / 2)
                });
                break;
            case "top":
                temp.css({
                    ...cssOption,
                    left: left,
                    top: top - tipHeight - defaultOption.space
                });
                break;
            case "bottom":
                temp.css({
                    ...cssOption,
                    left: left,
                    top: top + height + defaultOption.space
                });
                break;
        }

        setTimeout(function () {
            temp.css({
                opacity: 0,
                transform: "scale(0)"
            });
            setTimeout(function () {
                temp.remove();
            }, 500);
        }, 1000);
    };

    //post 请求
    Moi.prototype.ajax = function (option) {
        const slef = this;
        option.url = `/homeapi${option.url}`;
        // console.log(option)
        const copyOption = Object.assign({},option);
        copyOption['success'] = function(res){
            // 统一错误提示
            if(res.code ==  200000){
                alert(res.msg)
                return
            }else{
                option.success && option.success(res)
            }
        }
        $.ajax({
            headers: {
                // Token: slef.getCookie("Token"),
                "Content-Type": "application/json;charset=UTF-8"
            },
            // data: JSON.stringify(data),
            dataType: "json",
            ...copyOption
        });
    };

    //post 请求
    Moi.prototype.post = function (url, data, option) {
        url = `/homeapi/${url}`;
        this.ajax({
            url: url,
            type: "post",
            data: JSON.stringify(data),
            ...option
        });
    };

    //get 请求
    Moi.prototype.get = function (url, data, option) {
        this.ajax({
            url: url,
            type: "get",
            data: data,
            ...option
        });
    };

    //del 请求
    Moi.prototype.del = function (url, data, option) {
        this.ajax({
            url: url,
            type: "delete",
            data: JSON.stringify(data),
            ...option
        });
    };

    //设置页面数据
    Moi.prototype.setPageStorage = function (key, option) {
        this.pageStorage[key] = JSON.parse(JSON.stringify(option));
    };

    //获取页面数据
    Moi.prototype.getPageStorage = function (key, defaultParams) {
        return this.pageStorage[key] || defaultParams;
    };

    //获取页面数据
    Moi.prototype.quantity = function (option) {
        const quantityDom = option.dom;
        const valueDom = quantityDom.find(".product-calculator-value");
        const handleDom = quantityDom.find(".product-calculator-handle");
        handleDom.click(function () {
            const type = $(this).data("type");
            var value = parseInt(valueDom.val()) || 1;

            if(valueDom.attr("type") !== 'number'){
                value = valueDom.html();
            }

            if (type == "reduce" && value != 1) {
                
                if(valueDom.attr("type") == 'number'){
                    valueDom.val(--value);
                }else{
                    valueDom.html(--value);
                }

            }
            if (type == "add") {
                if(valueDom.attr("type") == 'number'){
                    valueDom.val(++value);
                }else{
                    const maxQuantity = storeConfig.one_sku_number_limit || 99999;
                    if(value < maxQuantity) { 
                        valueDom.html(++value);
                    }
                }
            }

            option.change && option.change.call(this, { value: value, type: type });
        });

        valueDom.on('input',function(){
            if(parseInt($(this).val()) < 1) { $(this).val(1) }
            if(parseInt($(this).val()) > 99999) { $(this).val(99999) }
            option.change && option.change.call(this, { value: $(this).val(), type: 'input' });
        })
    };

    //监听A标签调整
    Moi.prototype.bindRedirectHref = function (node) {
        const self = this;
        const theme_id = this.getUrlParam("theme_id");
        // document.get
        if (theme_id) {
            const ADOM = node || $("a");
            ADOM.on("click", function (e) {
                e.preventDefault();
                const href = $(this).attr("href");

                if (href === "javascript:;") {
                    // self.alertInfo({ content: $(this).data("tips") || "请添加" });
                    return;
                }

                if (href.indexOf("?") === -1) {
                    location.href = `${href}?theme_id=${theme_id}`;
                } else {
                    location.href = `${href}&theme_id=${theme_id}`;
                }
            });
        }
    };

    //跳转页面
    Moi.prototype.href = function (URL) {
        let url = URL;
        const theme_id = this.getUrlParam("theme_id");
        //是否有主题id
        if (theme_id) {
            if (url) {
                const splitStr = url.indexOf("?") === -1 ? "?" : "&";
                url = `${URL}${splitStr}theme_id=${theme_id}`;
            } else {
                this.alertInfo({ content: "请添加链接" });
                return false;
            }
        }
        location.href = url;
    };

    

    Moi.prototype.appendLoading = function ({ size = 50, container, theme, position } = {}) {
        $(container).css("pointer-events", "none").css("position", "relative");
        const style = document.createElement("style");
        style.innerHTML = `
           #common_tool-loading {
              position: ${position ? position : container ? "absolute" : "fixed"};
              top: 0; left: 0; bottom: 0; right: 0;
              background: ${theme ? (theme === "dark" ? "rgba(0, 0, 0, .8)" : "#ffffffe6") : ""};
              display: flex;
              align-items: center;
              justify-content: center;
              transition: opacity .2s linear;
              z-index:1000;
           }
           #common_tool-loading svg {
              animation: common_tool-loading-spin 1s linear infinite;
              fill: ${theme && theme === "dark" ? "#fff" : "#666"}
           }
           @keyframes common_tool-loading-spin {
              from { transform: rotate(0deg); }
              to { transform: rotate(360deg); }
           }
        `;
        const loading = `
           <div id="common_tool-loading">
              <svg width="${size}" height="${size}" t="1644634233141" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11473"><path d="M270.4 214.4C336 160 420 128 512 128c212 0 384 172 384 384h64c0-247.2-200.8-448-448-448-107.2 0-205.6 37.6-282.4 100l40.8 50.4z" p-id="11474"></path></svg>
           </div>
        `;
        document.head.appendChild(style);
        $(container || "body").append(loading);
    };

    Moi.prototype.removeLoading = function (container) {
        $(container).css("pointer-events", "");
        const $loading = $(container || "body").children('#common_tool-loading').css("opacity", 0);
        setTimeout(() => $loading.remove(), 200);
    };
    Moi.prototype.popup = function (option) {
        const defaultOption = Object.assign({ load: true, animated: true, customClass: "" }, option);
        const temp = $('<div class="mo-popup"><div class="mo-popup-mask popup-claer"></div><div class="mo-popup-body ' + defaultOption.customClass + '"><div class="mo-popup-content"></div></div></div>');
        const content = temp.find(".mo-popup-content");
        let load = false;

        if (defaultOption.load) {
            load = moi.nodeShowLoading(content, "mo-loading-black");
        }

        const returnOption = {
            temp: temp,
            load: load,
            showLoading() {
                returnOption.load = moi.nodeShowLoading(temp.find(".mo-popup-content"), "mo-loading-black");
                return load;
            },
            hideLoading() {
                returnOption.load && returnOption.load.close();
            },
            close(callback) {
                defaultOption.animated && content.addClass("animated bounceOutUp");
                setTimeout(function () {
                    temp.remove();
                    callback && callback();
                }, 800);
            },
            addContent(html) {
                defaultOption.load && load.close();
                content.append(html);
                defaultOption.animated && content.addClass("animated bounceInDown");
                const closeNodes = temp.find(".popup-claer");

                closeNodes.on("click", function () {
                    returnOption.close();
                });
            }
        };

        returnOption.showLoading();
        $("body").append(temp);

        return returnOption;
    };

    Moi.prototype.createScript = function (URL, callback) {

        const self = this;

        // var newUrl = this.setUrlParams(URL,{v:new Date().getTime()})
        //当前url的script
        const currentScript = $("script[src='" + URL + "']");

        //是否存在；存在直接执行
        if (currentScript.length) {
            callback && callback();
            return;
        }

        //创建一个script标签
        const script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", URL);
        script.onload = function () {
            self.onEvent("scriptSuccess",{url:URL})
            callback && callback();
        };

        script.onerror = function () {
            self.onEvent("scriptFail",{url:URL})
        };
        document.body.appendChild(script);
    };

    /**
     *
     * @param {*} videoId 视频id
     * @param {*} vedioContainer 视频容器
     * @param {*} height 视频高度，默认300
     * @param {*} width 视频宽度，默认全屏
     * @param {*} config 配置文件，播放参数
     */
    Moi.prototype.youtubeVideoPlay = function (vedioContainer, option) {
        if (!vedioContainer) throw "视频容器不能为空";
        this.createScript("https://www.youtube.com/iframe_api", () => {
            const timer = setInterval(() => {
                if (window.YT && YT.Player) {
                    clearInterval(timer);
                    const player = new YT.Player(vedioContainer, option);
                    option.success && option.success.call(this, player);
                }
            }, 300);
        });
    };

    //弹出商品预览
    Moi.prototype.popupProductPicture = function (option) {
        if (!this.ProductPictureShake) {
            return false;
        }
        const theme_id = this.getUrlParam("theme_id");
        // from
        this.globalpopupLayer = this.popup({ customClass: "popup-quick-body" });
        this.globalpopupLayer.addContent(`<div class="quick-iframe-wrap"><div class="quick-iframe-wrap-loading"></div><iframe class="quick-iframe" scrolling="no" id="quick-iframe" src="/products/${option.handle}?&quick_view=1&data_from=${option.data_from}"></iframe></div>`);
    };

    //弹出商品选择加入购物车
    Moi.prototype.popupProduct = function (option) {
        if (!this.ProductShake) {
            return false;
        }

        const self = this;

        const lang = window.lang;

        const popupLayer = this.popup();
        this.ProductShake = false;
        getProductInfo(option.handle, function (ret) {
            const retData = ret.data.product;
            self.ProductShake = true;
            //添加购物车
            function addCart(load) {
                moi.ajax({
                    url: "/cart/add",
                    type: "post",
                    data: JSON.stringify({
                        product_id: retData.id,
                        sku_code: retData.variant.sku_code,
                        quantity: 1,
                        data_from: self.getUrlParam("data_from")
                    }),
                    complete() {
                        load && load.close();
                    },
                    success: function (data) {
                        if (!data.code) {
                            temp.remove();
                            miniCart();
                            const unm = parseInt($("#cart_number").text() || 0) + 1;
                            $("#cart_number")
                                .show()
                                .html(unm > 99 ? 99 + "+" : unm);
                            $(".minicart").addClass("minicart_on");
                            oemasaasAddCardScriptScope && oemasaasAddCardScriptScope();
                        } else {
                            return self.alert({
                                title: data.msg
                            });
                        }
                    }
                });
            }

            if (retData.variants.length === 1) {
                popupLayer.close();
                addCart();
                return;
            }

            engine
                .parseAndRender($("#omesaas-popup-addPurchase").html(), {
                    product: retData,
                    lang: lang
                })
                .then(function (html) {
                    popupLayer.addContent(html);
                    const temp = popupLayer.temp;
                    const productDetail = new omesaasProduct({
                        product: retData,
                        id: temp.find("#buy-sku-option")
                    });

                    self.quantity({
                        dom: temp.find(".mo-quantity"),
                        change(val) {
                            productDetail.setSelectedVal({ quantity: val.value });
                        }
                    });

                    //加入购物车
                    temp.find("[data-type='cart']").click(function () {
                        if (!productDetail.verifyOption("cart")) {
                            return false;
                        }

                        var load = self.nodeShowLoading(this, "mo-loading-black");
                        productDetail.addCart(
                            function () {
                                load.close();
                            },
                            function (data) {
                                if (!data.code) {
                                    popupLayer.close(function () {
                                        $(".minicart").addClass("minicart_on");
                                    });
                                } else {
                                    return self.alert({
                                        title: data.msg
                                    });
                                }
                            }
                        );
                    });
                    //直接购买
                    temp.find("[data-type='buy_now']").click(function () {
                        if (!productDetail.verifyOption("buy")) {
                            return false;
                        }

                        var load = self.nodeShowLoading(this);

                        productDetail.buynow(
                            function () {
                                load.close();
                            },
                            function (ret) {
                                if (!ret.code) {
                                    self.href(ret.data.checkout_url);
                                } else {
                                    return self.alert({
                                        title: ret.msg
                                    });
                                }
                            }
                        );
                    });
                });
        });
    };

    //过滤设置当前语言
    Moi.prototype.getLanguage = function (language) {
        if (language[oemcart_website_language]) {
            return language[oemcart_website_language];
        }
        return "";
    };

    //格式化时间
    Moi.prototype.formatDate = function (date, format) {
        let we = date.getDay(); // 星期
        let z = getWeek(date); // 周
        let qut = Math.floor((date.getMonth() + 3) / 3).toString(); // 季度
        const opt = {
            "Y+": date.getFullYear().toString(), // 年
            "m+": (date.getMonth() + 1).toString(), // 月(月份从0开始，要+1)
            "d+": date.getDate().toString(), // 日
            "H+": date.getHours().toString(), // 时
            "M+": date.getMinutes().toString(), // 分
            "S+": date.getSeconds().toString(), // 秒
            "q+": qut // 季度
        };
        // 中文数字 (星期)
        const week = {
            0: "日",
            1: "一",
            2: "二",
            3: "三",
            4: "四",
            5: "五",
            6: "六"
        };
        // 中文数字（季度）
        const quarter = {
            1: "一",
            2: "二",
            3: "三",
            4: "四"
        };
        if (/(W+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? "星期" + week[we] : "周" + week[we]) : week[we]);
        if (/(Q+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 4 ? "第" + quarter[qut] + "季度" : quarter[qut]);
        if (/(Z+)/.test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 3 ? "第" + z + "周" : z + "");
        for (let k in opt) {
            let r = new RegExp("(" + k + ")").exec(format);
            // 若输入的长度不为1，则前面补零
            if (r) format = format.replace(r[1], RegExp.$1.length == 1 ? opt[k] : opt[k].padStart(RegExp.$1.length, "0"));
        }
        return format;
    };

    //生成随机数
    Moi.prototype.randomInteger = function (minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            default:
                throw new Error("仅允许传入1~2个参数");
        }
    };
    //时区时间时间戳格式
    Moi.prototype.formatZoneDate = function (value, format) {
        if (!value) {
            return "";
        }
        // return value.split('T')[0]
        // let time = 0;
        // if (typeof value === "string") {
        //     // return this.formatZoneDateStr(value,format)
        //     time = new Date(value).getTime();
        // } else {
        //     time = value * 1000; // new Date().getTime();
        // }
        // const sys_time = oemcart_time_zone;
        // const reg = RegExp(/-/); //这儿注意有坑。。如果包含了-则不需要处理如果包含了+需要加上-, 后端php无法处理这个问题所以这儿反向判断了。。
        // const data = reg.test(sys_time) ? Number(sys_time.split(/[-|+]/)[1]) : -Number(sys_time.split(/[-|+]/)[1]);
        // const newData = ((isNaN(data) ? 0 : data) - moment().parseZone().utcOffset() / 60) * 60 * 60 * 1000 + time;
        // console.log(value,new Date(newData))
        // return this.formatDate(new Date(newData), format);

        const sys_time = oemcart_time_zone;
        const reg = RegExp(/-/); //这儿注意有坑。。如果包含了-则不需要处理如果包含了+需要加上-, 后端php无法处理这个问题所以这儿反向判断了。。
        var data = 0;
        if (sys_time.indexOf("-") > -1 || sys_time.indexOf("+") > -1) {
            data = reg.test(sys_time) ? Number(sys_time.split(/[-|+]/)[1]) : -Number(sys_time.split(/[-|+]/)[1]);
        }
        const timeZone = parseInt(new Date().getTimezoneOffset() / 60) + parseInt(data);
        return this.formatDate(new Date(timeZone * 60 * 60 * 1000 + value * 1000), format);
    };

    //节流
    Moi.prototype.throttle = function (func, wait) {
        //之前的时间戳
        let old = 0;
        return function () {
            //获取当前的时间戳
            let now = new Date().valueOf();
            if (now - old > wait) {
                //立即执行
                func.apply(this, arguments);

                old = now;
            }
        };
    };

    //防抖
    Moi.prototype.debounce = function (func, delay) {
        let timer = null;
        return function () {
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, arguments);
            }, delay);
        };
    };

    document.addEventListener("changeCartNum", function (event) {
        var num = event.detail.num;
        if (num > 99) {
            num = "99+";
        }
        if (num) {
            $("#cart_number").show().html(num);
        } else {
            $("#cart_number").hide();
        }
    });

    Moi.prototype.changeCartNumber = function (num) {
        this.setPageStorage("cart_number", num);
        const event = new CustomEvent("changeCartNum", {
            detail: {
                num: num
            }
        });
        document.dispatchEvent(event);
    };

    Moi.prototype.showMiniCart = function () {
        $(".minicart").addClass("minicart_on");
    };
    /**
     * @description: 预览图片
     * @param {*} urls 图片集合
     * @param {*} index 当前预览
     * @param {*} self 点击元素
     * @return {*}
     */
    Moi.prototype.pictureImages = function (urls, index, self) {
        const tempHtml = $(`
        <div class="view-picture">
        <div class="view-picture-swiper" id="picture-swiper-container">
          <ul class="swiper-wrapper" style="width:100%"></ul>
        </div>
        <div class="view-picture-operate">
          <div class="operate-arrow-right" id='picture-swiper-prev'>
            <svg t="1635160440262" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1353" width="20" height="20"><path d="M511.609097 961.619254" p-id="1354"></path><path d="M360.749204 511.010463 360.749204 511.010463l382.080022-382.074905c14.762215-14.788821 14.762215-38.777165 0-53.585429-14.812357-14.788821-38.799678-14.788821-53.607942 0L283.415908 481.201553c-1.107217 0.867764-2.190899 1.824555-3.206018 2.843768-14.788821 14.808264-14.788821 38.795585 0 53.585429l408.226518 408.230612c14.808264 14.807241 38.795585 14.807241 53.584406 0 14.785751-14.767332 14.785751-38.754652 0-53.562916L360.749204 511.010463 360.749204 511.010463zM360.749204 511.010463" p-id="1355"></path></svg>
          </div>
          <div class="operate-arrow-close" id="operate-close">
            <svg t="1633405599567" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1984" width="20" height="20"><path d="M453.44 512L161.472 220.032a41.408 41.408 0 0 1 58.56-58.56L512 453.44 803.968 161.472a41.408 41.408 0 0 1 58.56 58.56L570.56 512l291.968 291.968a41.408 41.408 0 0 1-58.56 58.56L512 570.56 220.032 862.528a41.408 41.408 0 0 1-58.56-58.56L453.44 512z" p-id="1985"></path></svg>
          </div>
          <div class="operate-arrow-left" id='picture-swiper-next'>
            <svg t="1633330597342" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2631" width="20" height="20"><path d="M765.7 486.8L314.9 134.7c-5.3-4.1-12.9-0.4-12.9 6.3v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1c16.4-12.8 16.4-37.6 0-50.4z" p-id="2632"></path></svg>
          </div>
        </div>
      </div>
        `);
        let swiperSlideHtml = "";

        for (let i = 0; i < urls.length; i++) {
            swiperSlideHtml += `<li class="swiper-slide"><img src="${urls[i]}"></li>`;
        }

        tempHtml.find(".swiper-wrapper").append(`<li class="swiper-slide"><img src="${urls[index]}"></li>`);

        const top = self.offset().top - $(document).scrollTop();
        const left = self.offset().left;
        const height = self.height();
        const width = self.width();

        tempHtml.css({ height: height, top: top, left: left, width: width, opacity: 0.1 });
        $("body").append(tempHtml);

        setTimeout(function () {
            tempHtml.css({ height: "100%", top: 0, left: 0, width: "100%", opacity: 1 });
        }, 100);

        setTimeout(function () {
            tempHtml.css({ backgroundColor: "rgba(0, 0, 0, 0.6)" });

            tempHtml.addClass("view-picture-operate-show");

            tempHtml.find(".swiper-wrapper").html(swiperSlideHtml);

            new Swiper("#picture-swiper-container", {
                loop: false,
                initialSlide: index,
                autoHeight: true,
                navigation: {
                    nextEl: "#picture-swiper-next",
                    prevEl: "#picture-swiper-prev"
                }
            });
        }, 800);

        tempHtml.find("#operate-close").click(function () {
            tempHtml.addClass("view-picture-operate-hide");
            tempHtml.css({ opacity: 0.1 });
            setTimeout(function () {
                tempHtml.remove();
            }, 400);
        });
    };

    Moi.prototype.countdown = function (dom, time, callback) {
        var time;
        var t = setInterval(function () {
            if (time <= 0) {
                dom.remove();
                callback && callback();
                clearInterval(t);
            }
            var s = Math.floor(time % 60);
            var m = Math.floor((time / 60) % 60);
            var h = Math.floor((time / (60 * 60)) % 60);
            time = parseFloat(time) - 1;
            var HHtml = '<span style="padding:5px;font-size:14px;line-height:1;color:#EC4330;background-color:#FFF0EF;border-radius:2px;">' + (h >= 10 ? h : "0" + h) + "H</span>";
            var mHtml = '<span style="padding:5px;font-size:14px;line-height:1;color:#EC4330;background-color:#FFF0EF;border-radius:2px;">' + (m >= 10 ? m : "0" + m) + "M</span>";
            var sHtml = '<span style="padding:5px;font-size:14px;line-height:1;color:#EC4330;background-color:#FFF0EF;border-radius:2px;">' + (s >= 10 ? s : "0" + s) + "S</span>";
            var str = "";
            if(h > 0){
                 str = HHtml + "&nbsp;:&nbsp;" + mHtml + "&nbsp;:&nbsp;" + sHtml;
            }else{
                 str = mHtml + "&nbsp;:&nbsp;" + sHtml;
            }
            dom && dom.html(str);
        }, 1000);
    };

    function setMoreMenu(option){
        var parentNode = $(option.parent);
        var childNode = parentNode.find(option.child);
        var moreNode = parentNode.find(option.moreClass);
        var parentWidth = parentNode.innerWidth();
        var totalWidth =  0;
        var moreNodeWidth = moreNode.innerWidth();
        var isMore = false;
        childNode.each(function (index, child) {
            totalWidth += $(child).innerWidth();
            if (!$(child).hasClass(option.moreClass.replace('.','')) && totalWidth + moreNodeWidth > parentWidth ) {
                $(child).hide();
                isMore = true;
            }
        });

        option.moreHtml && parentNode.append( option.moreHtml);
        isMore ? moreNode.show() : moreNode.hide()
        if(option.triggerFunc === 'click' || !option.triggerFunc){
            moreNode.click(function(e){
                e.stopPropagation()
                option.onMore && option.onMore()
            })
        }else {
            moreNode.hover(function(e) {
                e.stopPropagation()
                option.hoverEnter && option.hoverEnter()
            },function(e) {
                e.stopPropagation()
                option.hoverLeave && option.hoverLeave()
            })
        }
    }

    

    Moi.prototype.setCustomNav = function (d,w,isShowShortMenu = false, callbackFunc) {
        d.find('.nav-child').each(function(){
            if(isShowShortMenu) {
                if($(this).find('dl dd').length > 0){
                    $(this).parents('li').addClass('nav-child-three');
                }else {
                    $(this).parents('li').addClass('nav-child-second');
                }
            }else {
                $(this).parents('li').addClass('nav-child-three');
            }
        })
        var navWidth = w;
        var navUl = d.children('ul').width();
        if(navUl > navWidth){ 
            d.children('ul').children('li').each(function(){
                var left = $(this).position().left;
                var w = $(this).width();
                left += w;
                if(left > (navWidth - 160)){
                    $(this).hide();
                    $(this).nextAll('li').hide();
                    return false;
                }
            })
            d.children('ul').append('<li class="more_link"><span><a class="nav-li-a" href="javascript:void(0)">'+lang.general.more_link+'</a></span><div class="more_link_child"><div class="nav_container_wrapper"></div></div></li>');
            var _html = d.children('ul').clone();
            d.find('.more_link_child').children('.nav_container_wrapper').append(_html);
            d.find('.more_link_child').children('.nav_container_wrapper').children('ul').children('li').each(function(index){
                if($(this).is(':visible')){
                  $(this).remove();
                }else{
                  if(d.find('.more_link_child').children('.nav_container_wrapper').children('ul').find('li.on').length === 0) {
                    $(this).addClass('on')
                  }
                  $(this).show();
                }
                
            })
            d.find('.more_link_child').children('.nav_container_wrapper').children('ul').children('li').hover(function(){
                $(this).parent().siblings('.nav-child').remove();
                $(this).parent().children('li').removeClass('on');
                $(this).addClass('on');
                if($(this).children('.nav-child').length == 1){
                    var moreNav = $(this).children('.nav-child').clone();
                    $(this).parent().parent().append(moreNav);
                }
            })
            
        }
        d.children('ul').css('width', '100%')
        callbackFunc && callbackFunc()
    }

    Moi.prototype.setHeadMenu = function (option) {
        setMoreMenu(option)
        this.addEvent('lazyImg', function(event) {
            if (option.logoSrc && event.params == option.logoSrc) {
                setMoreMenu(option)
            }
        })
    };


    window.moi = new Moi();

    function getWeek(dateTime) {
        let temptTime = new Date(dateTime.getTime());
        // 周几
        let weekday = temptTime.getDay() || 7;
        // 周1+5天=周六
        temptTime.setDate(temptTime.getDate() - weekday + 1 + 5);
        let firstDay = new Date(temptTime.getFullYear(), 0, 1);
        let dayOfWeek = firstDay.getDay();
        let spendDay = 1;
        if (dayOfWeek != 0) spendDay = 7 - dayOfWeek + 1;
        firstDay = new Date(temptTime.getFullYear(), 0, 1 + spendDay);
        let d = Math.ceil((temptTime.valueOf() - firstDay.valueOf()) / 86400000);
        let result = Math.ceil(d / 7);
        return result;
    }

    function getProductInfo(handle, success) {
        moi.ajax({
            url: `/products/${handle}`,
            type: "get",
            success: function (ret) {
                if (!ret.code) {
                    success && success.call(this, ret);
                } else {
                    return moi.alert({
                        title: ret.msg
                    });
                }
            }
        });
    }

    //关闭快速预览
    window.quickViewClose = function (callback) {
        if (moi.globalpopupLayer) {
            moi.globalpopupLayer.close(callback);
        }
    };
    //快速预览加入购物车
    window.quickViewCart = function (params) {
        moi.onEvent("cartChange", params.cart);
        moi.addEvent(
            "quickViewAddCart",
            function () {
                showMiniCart();
            },
            true
        );
        quickViewClose(function () {
            var num = parseInt(moi.getPageStorage("cart_number", 0)) + params.quantity;
            moi.changeCartNumber(num);
            miniCart();
            moi.onEvent("quickViewAddCart", {
                product_id: params.product_id,
                product:params,
                collection_id: []
            });
        });
    };
    //快速预览立即购买
    window.quickViewBuy = function (url) {
        quickViewClose(function () {
            moi.href(url);
        });
    };
    //查看详情
    window.quickViewDetail = function (url) {
        quickViewClose(function () {
            moi.href(url);
        });
    };

    //显示快速预览
    window.quickViewLoad = function (height) {
        if (!moi.globalpopupLayer) {
            return false;
        }

        const classStr = themeConfig.global.product_quickview_type == "normal" ? "normal-quick-iframe" : "simple-quick-iframe";
        const quickIframe = moi.globalpopupLayer.temp.find("#quick-iframe");
        const iframeWrapNode = moi.globalpopupLayer.temp.find(".quick-iframe-wrap");
        moi.globalpopupLayer.temp.find(".quick-iframe-wrap-loading").remove();
        quickIframe.height(height);
        quickIframe.addClass(classStr);

        setTimeout(function () {
            if (height > iframeWrapNode.innerHeight()) {
                quickIframe.attr("scrolling", "auto");
            }
        }, 500);
    };
    window.oemsaasQuickview = moi.throttle(function (e) {
        e.stopPropagation();
        e.preventDefault();
        moi.popupProductPicture({
            handle: $(this).data("handle"),
            data_from: $(this).data("from")
        });
    }, 1000);

    window['quickview'] = moi.throttle(function (e) {
        e.stopPropagation();
        e.preventDefault();
        moi.popupProductPicture({
            handle: $(this).data("handle"),
            data_from: $(this).data("from")
        });
    }, 1000);


   

    // 用户点击追加页面
    // function pageHandleClick(){
    //     var is_user_push_state = false;
    //     function userTriggerPushState(){
    //         if(!is_user_push_state){
    //             addRouter(true)
    //             is_user_push_state = true
    //         }
    //     }
    //     document.addEventListener("click",userTriggerPushState)
    // }

    // var pageRouters = [];
    // var routerPage = 500;

    function getFirstUrl(){
        return sessionStorage.getItem("firstUrl") || false;
    }

    function createdExitIntentToken(){
        return new Date().getTime() + Math.floor(Math.random() * 10)
    }

    const oemcartRouter={
        list:[],
        addRouter(){
            router.list.push(location.href)
        },
        saveLocalStorage(){
            localStorage.setItem('oemcart_routers',JSON.stringify(router.list))
        }
    }

    const firstWindowExitIntentUtil = {
        // 获取exit_intent_token
        getExitIntentToken(){
            return moi.getCookie("exit_intent_token")
        },
        // exit_intent_first_window 代表未第一个页面
        isExitIntentFirst(){
            return sessionStorage.getItem("exit_intent_first_window")
        },
        // 设置exit_intent_token和exit_intent_first_window
        setValue(){
            sessionStorage.setItem("exit_intent_first_window",1);
            moi.setCookie("exit_intent_token",createdExitIntentToken(),  window["exit_intent_expiration_date"] || 'h1')
        },
        // 删除数据
        removeValue(){
            sessionStorage.removeItem("exit_intent_first_window");
            sessionStorage.removeItem("firstUrl")
            moi.delCookie("exit_intent_token");
        }
    }

    
    function isHandleExit(state){
        var firstUrl = getFirstUrl();
        var href = location.href;
        // 如果不存在state 代表第一页
        if(!state && firstUrl == href){
            return true
        }
        return false
    }


    // 事件注册触发
    function handleCallBackExitIntent(){
        // 删除缓存
        firstWindowExitIntentUtil.removeValue()
        moi.onEvent("callback_exit_intent")
        window["callback_exit_intent"] && callback_exit_intent()
    }

    // 页面切换
    function addEventListenerPopstate(){
        window.addEventListener("popstate", (event) => {
            if(window["oemcart_is_debug"]){
                var exit_intent_first_window = sessionStorage.getItem("exit_intent_first_window");
                var firstUrl = sessionStorage.getItem("firstUrl")
                var exit_intent_token = moi.getCookie("exit_intent_token");
                $('body').append(`<div>${JSON.stringify({exit_intent_first_window,firstUrl,exit_intent_token})}</div>`)
            }
            if(isHandleExit(event.state) && firstWindowExitIntentUtil.isExitIntentFirst()){
                handleCallBackExitIntent();
            }
        });
    }

    function addRouter(isReplace){
        history.pushState({ page: 403 }, "",moi.setUrlParams(location.href,{exit:'true'}));
        // ++routerPage;
        // pageRouters.push(routerPage)
        // if(isReplace){
        //     history.replaceState({ page: routerPage },"",moi.setUrlParams(location.href,{exit:'true'}));
        // }else{
        //     history.pushState({ page: routerPage }, "",moi.setUrlParams(location.href,{exit:'true'}));
        // }
    }

    var is_init_exit_intent = false;
    window["init_exit_intent"] = function init_exit_intent(option){
        // 测试模式
        if(option && option.debug){
            window["oemcart_is_debug"] = true;
        }

        // 测试模式
        if(option && option.cookieExpirationDate){
            window["exit_intent_expiration_date"] = option.cookieExpirationDate;
        }

        // 是否函数已经执行过一次
        if(is_init_exit_intent) {
            return false
        }

        
        
        if(moi.isMobile()){ 
            //移动端执行逻辑
            var firstUrl = getFirstUrl();
            var href = location.href;
            // 如果不存在设置第一次进入的url
            //  || (href == firstUrl)
            // !firstUrl && 
            if((!firstWindowExitIntentUtil.getExitIntentToken())){
                sessionStorage.setItem("firstUrl",href)
                addRouter()
            }
            addEventListenerPopstate();
        }else{ 
            //电脑端执行
            // 监听鼠标上方移除body
            document.body.addEventListener('mouseout', function(event) {
                if (event.clientY < 0 && firstWindowExitIntentUtil.isExitIntentFirst()) {
                    handleCallBackExitIntent();
                }
            });
        }


        // 是否已经缓存第一个页面的cookie
        if(!firstWindowExitIntentUtil.getExitIntentToken()){
            firstWindowExitIntentUtil.setValue()
        }

        is_init_exit_intent = true;
    }
    // http://mgr.oemsaas.shop/us01/git/mvasserttooss?theme_dir=default
    // // 检测是否有用户离开意图的事件
    // document.addEventListener("DOMContentLoaded",function(){
    //     window['init_exit_intent'] && window['init_exit_intent']({
    //         cookieExpirationDate:'1s',
    //         debug:true
    //     })
    // })

})();
function getOssProcess(){
    var oemcart_platform = window['oemcart_platform'] || 1;

    if(oemcart_platform == 1){
        return "x-oss-process=image"
    }else{
        return "x-image-process=image"
    }
}

function setOssProcessPath(src,imgHandleTypes){
    if(imgHandleTypes.length){
        var handleTypes = [getOssProcess()].concat(imgHandleTypes);
        var splitStr = src.indexOf("?") === -1 ? "?" : "&";
        return src + splitStr +  handleTypes.join("/");
    }
    return src
}

//瀑布流
(function () {
    function waterfalls(option) {
        const self = this;

        this.dom = $(option.id);

        //resize 配置
        this.resizeConfig = option.resizeConfig;

        //多少列
        this.currentColumnConfig = this.resizeWidth($(window).width()); //option.columns || 3;

        //每列间距
        this.columnsGutter = "20px";

        //渲染方式
        this.renderType = option.renderType || "Js";

        //每行间距
        this.rowGutter = "20px";

        //节点 $(option.id)
        this.fallNode = null;
        //子元素类名
        this.childrenClassName = option.childrenClass || ".mo-waterfall-column";

        //距离底部高度
        this.bottomDistance = option.bottomDistance || 30;

        //渲染方法
        this.render = option.render;

        //获取图片数据key
        this.imgKey = option.imgKey || false;

        //窗口可见高度
        this.windowH = $(window).height();

        //滚动到底部
        this.scrollBottom = option.scrollBottom;

        //渲染完成
        this.renderComplete = option.renderComplete;

        //加载样式
        this.loadHtml = $('<div class="mo-waterfall-status-box"><div class="loading-box"></div></div>');

        //加载所有样式

        // this.allHtml = $('<div class="mo-waterfall-allLoad">价值</div>')

        //数据缓存
        this.storage = [];

        //添加高度
        this.addHeight = option.addHeight;

        //初始化·
        this.initDom();

        //滚动事件监听
        $(window).scroll(function () {
            // const theme_id = moi.getUrlParam("theme_id");
            // if (!theme_id) {
            self.scroll.call(this, self);
            // }
        });

        //页面大小变化监听
        $(window).resize(function () {
            const width = $(window).width();
            const columns = self.resizeWidth(width);
            if (columns && columns.columns !== self.currentColumnConfig.columns) {
                self.refresh(columns);
            }
        });
    }

    //获取宽度布局
    waterfalls.prototype.resizeWidth = function (width) {
        for (let i = 0; i < this.resizeConfig.length; i++) {
            const config = this.resizeConfig[i];
            if (config.min <= width && (width <= config.max || !config.max)) {
                return config;
            }
        }
        return false;
    };

    //重新初始化
    //渲染数据
    waterfalls.prototype.refresh = function (columns) {
        this.currentColumnConfig = columns;
        this.dom.empty();
        this.initDom();
        this.storageRender(this.storage);
    };

    //渲染默认数据
    waterfalls.prototype.RenderDefaultData = function (data, moreText) {
        const list = [];
        for (let index = 0; index < this.currentColumnConfig.columns * 3; index++) {
            list.push(data);
        }
        this.storageRender(list);
        this.showMore(moreText, "javascript:;");
    };

    //初始化dom渲染列
    waterfalls.prototype.initDom = function () {
        this.dom.append(`<div class="mo-waterfall-warp"></div>`);

        this.fallNode = this.dom.children(".mo-waterfall-warp");
        //追加列数据
        for (let i = 0; i < this.currentColumnConfig.columns; i++) {
            const element = $(`<div class="mo-waterfall-column" style="--row-gutter:${this.currentColumnConfig.rowGutter}"></div>`);
            this.fallNode.append(element);
        }

        //设置css 变量属性
        this.fallNode.attr("style", `--columns:${this.currentColumnConfig.columns};--column-gutter:${this.currentColumnConfig.columnsGutter}`);

        //子元素
        this.childs = this.getChilds();
    };

    //追加数据
    waterfalls.prototype.addStorage = function (data) {
        this.storage = [...this.storage, ...data];
        this.storageRender(data);
    };

    waterfalls.prototype.getImageHeight = function (src, callback, i) {
        if (!src) {
            callback && callback(0);
            return;
        }
        let image = new Image();
        image.src = setOssProcessPath(src,['resize,m_lfit,w_100']);
        image.onload = () => {
            const scale = image.height / image.width;
            const proportional = (this.childs.width * scale).toFixed(2);
            callback && callback(Number(proportional));
        };
        image.onerror = () => {
            console.log("加载失败");
            callback && callback(0);
        };
    };

    //渲染数据
    waterfalls.prototype.storageRender = function (list) {
        const loadHtml = [];
        let sotrs = this.getChildsMinHeight();
        let startIndex = 0;
        // console.warn(startIndex)
        for (let i = 0; i < list.length; i++) {
            const index = sotrs[startIndex];
            if (!loadHtml[index]) {
                loadHtml[index] = [];
            }
            list[i]["currentIndex"] = i;
            if (this.renderType === "liquid") {
                loadHtml[index].push(list[i]);
            } else {
                loadHtml[index].push(this.render(list[i]));
            }
            startIndex = startIndex === this.childs.node.length - 1 ? 0 : startIndex + 1;
        }
        this.appendHTml(loadHtml);
    };

    waterfalls.prototype.forAppendHTml = function (loadHtml) {
        for (let i = 0; i < loadHtml.length; i++) {
            this.appendHTml(loadHtml[i].html, loadHtml[i].height);
        }
    };

    //获取瀑布流距离顶部高度
    waterfalls.prototype.getOffsetTop = function () {
        return (this.fallNode.offset() && this.fallNode.offset().top) || 0;
    };

    //获取窗口高度
    waterfalls.prototype.window = function () {
        return $(window).height();
    };

    //获取瀑布流高度
    waterfalls.prototype.getHeight = function () {
        return this.fallNode.height();
    };

    //获取子内容

    waterfalls.prototype.getChilds = function () {
        const node = this.fallNode.children(this.childrenClassName);
        const heights = [];
        for (let i = 0; i < node.length; i++) {
            heights.push({ index: i, height: node.eq(i).height() });
        }
        return {
            node,
            width: node.eq(0).width(),
            heights
        };
    };

    //获取子元素最小的高度
    waterfalls.prototype.getChildsMinHeight = function () {
        const childsHeight = this.childs.heights;
        const copyChildsHeight = JSON.parse(JSON.stringify(childsHeight));
        return copyChildsHeight
            .sort((a, b) => a.height - b.height)
            .map((item) => {
                return item.index;
            });
    };

    //设置高度
    waterfalls.prototype.setHeight = function (index, height) {
        this.childs.heights[index] = this.childs.heights[index] + height + this.addHeight();
    };

    //滚动事件
    waterfalls.prototype.scroll = function (self) {
        //滚动高度
        const scrollTop = $(this).scrollTop();

        if (scrollTop + self.windowH + self.bottomDistance >= self.getHeight() + self.getOffsetTop()) {
            //设置内容高度
            self.childs = self.getChilds();
            //执行回调方法
            self.scrollBottom && self.scrollBottom.call(this);
        }
    };

    waterfalls.prototype.complete = function () {
        moi.bindRedirectHref(this.fallNode.find("a"));
        this.renderComplete && this.renderComplete.call(this, this.fallNode);
    };

    //追加html
    waterfalls.prototype.appendHTml = function (loadHtml) {
        const self = this;
        const childsNode = this.childs.node;
        let completeCount = 0;
        for (let i = 0; i < loadHtml.length; i++) {
            if (loadHtml[i]) {
                //liquid
                if (this.renderType === "liquid") {
                    this.render(loadHtml[i], function (node) {
                        childsNode.eq(i).append(node);
                        self.renderComplete && self.renderComplete.call(this, node);
                        moi.onEvent("waterfallsComplete");
                    });
                } else {
                    //html追加
                    const node = $(loadHtml[i].join(""));
                    childsNode.eq(i).append(node);
                    self.renderComplete && self.renderComplete.call(this, node);
                    moi.onEvent("waterfallsComplete");
                }
            }
        }
    };

    //显示加载
    waterfalls.prototype.showLoad = function () {
        this.dom.append(this.loadHtml);
    };

    //隐藏
    waterfalls.prototype.hideLoad = function () {
        this.loadHtml.remove();
    };

    //显示加载完毕
    waterfalls.prototype.showAll = function (text) {
        this.dom.append($(`<div class="mo-waterfall-status-box"><span>${text}</span></div>`));
    };

    //显示加载更多
    waterfalls.prototype.showMore = function (text, href) {
        if (text) {
            this.dom.append($(`<div class="mo-waterfall-status-box"><a href='${href}' class="secondary_btn">${text}</a></div>`));
        }
    };

    window.waterfalls = waterfalls;

    //是否执行滚动加载事件
    window.waterfallsScrollLoad = true;

    window.waterfalls = waterfalls;
})();

// 加载webp图片判断浏览器是否支持webp;
var oemcartIsWebp = "";
function checkWebpFeature(feature, callback) {

    if(typeof oemcartIsWebp === "boolean"){
        return  callback(feature, oemcartIsWebp)
    }

    var kTestImages = {
        lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",
        lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==",
        alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==",
        animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA"
    }
    var img = new Image()
    img.onload = function () {
        oemcartIsWebp = (img.width > 0) && (img.height > 0)
        callback(feature, oemcartIsWebp)
    };
    img.onerror = function () {
        oemcartIsWebp = false;
        callback(feature, false)
    }
    img.src = "data:image/webp;base64," + kTestImages[feature]
}


//图片懒加载
(function () {
    // 获取window的引用:
    const $window = $(window);
    // 获取包含data-src属性的img，并以jQuery对象存入数组:
    // const lazyImgs = $('img[data-src]');

    //获取屏幕像素密度
    const ratio = window.devicePixelRatio;
    var lazyImgs = [];

    //获取图片配置
    function getStoreConfigImageConfig(){
        if(!window.storeConfig || !window.storeConfig.imagerocket){
            return false
        }
        // php返回为对象字符串需转化
        return JSON.parse(window.storeConfig.imagerocket);
    }

    //图片转webp
    function getImageToWebP(suffix){
        var config = getStoreConfigImageConfig();
        var webpSuffix = ["JPG","JPEG","PNG","AVIF"];

        if(!config || config.status == 2 || !webpSuffix.includes(suffix)){
            return ""
        }
        return `format,webp`
    }

    //图片质量改变
    function getImageQuality(suffix){
        var qualitySuffix = ["JPG","JPEG","WEBP"];
        //  || !qualitySuffix.includes(suffix)
        var config = getStoreConfigImageConfig();
        if(!config || config.status == 2 || (!getImageToWebP(suffix) && !qualitySuffix.includes(suffix))){
            return ""
        }
        var quality = config.quality_type === 1?'q':'Q';
        return `quality,${quality}_${config.quality_value}`
    }

    function avifFormatJPG(suffix){
        if(suffix === "AVIF"){
            return `format,jpg`
        }
        return ""
    }

    // 加载图片
    function loadImg(option) {
        var config = getStoreConfigImageConfig();
        
        // 是否支持webp
        checkWebpFeature("lossy", function (feature, isSupported) {
            if (isSupported) {
                option.imgHandleTypes.push(getImageToWebP(option.fileExtension));
            }
            if(!isSupported || config.status === 2 || !config){
                // 不支持webp 并且 AVIF格式 转jpg
                option.imgHandleTypes.push(avifFormatJPG(option.fileExtension))
            }




            option.elment[0].onload = () => {
                moi.onEvent("lazyImg", option.imgSrc);
            }
            option.elment[0].onerror = () => {
                if(!option.retry){
                    option.elment.attr("src", option.src);
                    option['retry'] = true
                }else{
                    // option.elment.attr("src", option.oldSrc);
                    if(option.elment.attr('flag')) {
                        option.elment.attr("src", oemcart_imgcdn+ "/uploads/0/theme/default/assets/guoqi.png");
                    }else {
                        option.elment.attr("src", oemcart_imgcdn+ "/uploads/0/theme/default/assets/empty.png");
                    }
                }
            }
    
            var handleTypes = option.imgHandleTypes.filter(Boolean);
            option.elment.attr("src", setOssProcessPath(option.src,handleTypes));
            // option.elment[0].onload = () => {
            //     moi.onEvent("lazyImg", option.imgSrc);
            // }
            // option.elment[0].onerror = () => {
            //     option.elment.attr("src", option.oldSrc);
            // }
    
            //  var splitStr = option.imgSrc.indexOf("?") === -1 ? "?" : "&";
            //  var handleTypes = option.imgHandleTypes.filter(Boolean);
            //  var newSrc = option.src;
            //  if(handleTypes.length){
            //     newSrc +=  splitStr + "x-oss-process=image/" +  handleTypes.join("/");
            //  }
            // option.elment.attr("src", newSrc);
        });

    }

    function setImgUrl(elment) {

        // elment.attr("oem-if",true);

        //避免店匠导入的图片懒加载规则冲突
        if (elment.attr("data-aspect-ratio")) {
            return false;
        }

        var oldSrc = elment.attr("src");
        // 设置src属性:
        var imgSrc = elment.attr("data-src");
        //裁剪方法
        var cropType = elment.attr("data-crop-type");

        //裁剪高度
        var cropHeight = elment.attr("data-crop-height");

        //裁剪宽带
        var cropWidth = elment.attr("data-crop-width");

        var isCdn = elment.attr("data-cdn") || false;

        //删除属性
        elment[0].removeAttribute("data-src");
        //如果有src属性加载src
        if (imgSrc) {

            // TODO 优化图片加载质量
            var fileExtension = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
            var src = imgSrc;
            
            // 如果路径是绝对记录拼接cdn地址 /uploads/0/theme/default/assets/block_high_search_bg.png
            // if(/^(?:\/|[a-z]+:\/\/)/i.test(src)){
            //     src = oemcart_imgcdn+src
            // }

            if(isCdn) {
                src = oemcart_imgcdn+src
            }
            // oss支持裁剪的文件后缀名
            var whiteSuffix = ["JPG","JPEG","PNG","BMP","TIFF","AVIF"];

            // 图片处理格式
            var imgHandleTypes = [];
            if(whiteSuffix.includes(fileExtension)){
                //默认宽度裁剪
                var width = cropWidth || elment.innerWidth();
                
                //高度裁剪
                if (cropType === "height") {
                    var height = cropHeight || elment.height();
                    if(height){
                        imgHandleTypes.push(`resize,m_lfit,h_${Math.floor(width * (ratio > 1 ? ratio : 1.5))}`);
                    }
                }else if (cropType === 'none') {//不裁剪
                    imgHandleTypes.push('')
                }else{
                    if(width){
                        imgHandleTypes.push(`resize,m_lfit,w_${Math.floor(width * (ratio > 1 ? ratio : 1.5))}`);
                    }
                }
                imgHandleTypes.push(getImageQuality(fileExtension));
            }

            loadImg({
                src: src,
                fileExtension:fileExtension,
                imgHandleTypes:imgHandleTypes,
                imgSrc:imgSrc,
                oldSrc:oldSrc,
                elment:elment
            });
        }
    }

    //加载图片
    function lazyImageShow() {
        // 获取页面滚动的高度:
        const wtop = $window.scrollTop();
        // 判断是否还有未加载的img:
        if (lazyImgs.length > 0) {
            // 获取可视区域高度:
            const wheight = $window.height();
            const delIndexs = [];
            for (let i = 0; i < lazyImgs.length; i++) {
                const $i = lazyImgs[i];
                // 判断是否在可视范围内:
                if ($i.offset().top - wtop - 100 < wheight && $i.is(":visible")) {
                    delIndexs.push(i);
                    setImgUrl($i);
                }
            }

            for (let i = delIndexs.length - 1; i >= 0; i--) {
                lazyImgs.splice(delIndexs[i], 1);
            }
        }
    }


    var isSupportIntersectionObserver = window['IntersectionObserver']?true:false;
    var imgObserver = "";

    if (isSupportIntersectionObserver) {
        imgObserver = new IntersectionObserver(
            function (entrys) {
                for (const entry of entrys) {
                    if (entry.intersectionRatio > 0) {
                        const element = $(entry.target);
                        setImgUrl(element);
                    }
                }
            },
            { rootMargin: "0px 0px 100px 0px", threshold: [0.01] }
        )
    }else{
        console.log("Not Supported IntersectionObserver")
    }

    // 定义事件函数:


    function onScroll() {
        if (!isSupportIntersectionObserver) {
            lazyImageShow();
        }
    };

    // 绑定事件:
    $window.scroll(onScroll);

    //懒加载
    window.lazyImageShow = lazyImageShow;
    window.lazyLoadImage= setImgUrl;

    window.addLazyImages = function (nodes) {
        nodes.each(function () {
            if (isSupportIntersectionObserver) {

                imgObserver.observe(this);
            } else {
                lazyImgs.push($(this));
            }
        });
        onScroll();
    };


        try {
            document.addEventListener('DOMContentLoaded', (event) => {
                $('html,body').find('img[data-src]').each(function(){
                    addLazyImages($(this))
                })
            })
            // 未添加的元素监听img 加载
            document.addEventListener('DOMNodeInserted', function (event) {
                var nodeImg = $(event.target);
                var lazyImgages = nodeImg.find("img[data-src]");
                if(lazyImgages.length){
                    lazyImgages.each(function(){
                        window.addLazyImages($(this))
                    })
                }
            }, false);

            // 选择目标节点
            // // var targetNode = document.getElementById('你的目标元素的ID');
            // if (window["MutationObserver"]) {

            //      // 创建观察器实例
            //     var observer = new MutationObserver(function (mutations) {
            //         mutations.forEach(function (mutation) {
            //             // 在这里处理变动
            //             //  if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
            //             //     $('html,body').find('img[data-src]').each(function(){
            //             //         window.addLazyImages($(this))
            //             //     })
            //             //     // var nodeImg = $(mutation.target);
            //             //     // var lazyImgages = nodeImg.find("img[data-src]");
            //             //     // if(lazyImgages.length){
            //             //     //     lazyImgages.each(function(){
            //             //     //         window.addLazyImages($(this))
            //             //     //     })
            //             //     // }
            //             // }
            //         });
            //     });
    
            //     // 观察器的配置
            //     var config = { childList: true,subtree: true };
    
            //     // 开始观察目标节点的变动
            //     observer.observe(document, config);
            // }
        
        } catch (error) {
            
        }
})();

// 比例裁剪
$(function () {
    // function getDefaultStyle(obj,attribute){ // 返回最终样式函数，兼容IE和DOM，设置参数：元素对象、样式特性
    //     return obj.currentStyle?obj.currentStyle[attribute]:document.defaultView.getComputedStyle(obj,false)[attribute];
    // }

    //商品列表图片比例
    function imgSize(productBox) {
        // const productBox = $(classID);
        for (let i = 0; i < productBox.length; i++) {
            var self = productBox.eq(i);
            if (self.data("scale")) {
                var data_scale = self.data("scale").toString();
                var productWidth = parseInt(self.width());
                if (data_scale === "none" || !productWidth) {
                    return false;
                }

                switch (data_scale) {
                    case "11":
                        self.css("height", productWidth);
                        break;
                    case "34":
                        self.css("height", (productWidth / 3) * 4);
                        break;
                    case "23":
                        self.css("height", (productWidth / 2) * 3);
                        break;
                    case "12":
                        self.css("height", (productWidth / 1) * 2);
                        break;
                    default:
                        break;
                }
                self.attr("data-scale", "none");
            }
        }
    }
    $(window).resize(function () {
        imgSize($(".product_img"));
    });

    $(window).load(function () {
        imgSize($(".product_img"));
    });
    imgSize($(".product_img"));

    window.productSize = imgSize;

    $("img").error(function () {
        $(this).attr("src",oemcart_imgcdn+ "/uploads/0/theme/default/assets/empty.png");
    });
});

//全局搜索方法
window.oemsaasSearch = function (classStr) {
    const themeId = moi.getUrlParam("theme_id");
    const searchValue = $.trim($(classStr).val());
    if (!searchValue) {
        return false;
    }
    const URL = location.href.indexOf("/search") > -1 ? location.href : "/search";
    location.href = moi.setUrlParams(URL, { q: searchValue, page: 1, theme_id: themeId });
    return false;
};
window['search'] = function (classStr) {
    const themeId = moi.getUrlParam("theme_id");
    const searchValue = $.trim($(classStr).val());
    if (!searchValue) {
        return false;
    }
    const URL = location.href.indexOf("/search") > -1 ? location.href : "/search";
    location.href = moi.setUrlParams(URL, { q: searchValue, page: 1, theme_id: themeId });
    return false;
};

window.oemsaasMiniCart = function () {
    moi.onEvent("showMiniCart");
    $(".minicart").addClass("minicart_on");
    const html = $(".minicart").find(".minicart_mid").html();
    if (!html) {
        miniCart();
    }else{
        var miniCartInfo = moi.getPageStorage('miniCartInfo',{coupon_code:''});
        oemcartCouponRecord && oemcartCouponRecord('',miniCartInfo.coupon_code)
        if(window["oemcart_current_template"] !== "cart_list"){
            oemcartTriggerCartChange();
        }

    }
};


window['showMiniCart'] = function () {
    window.oemsaasMiniCart()
};

/**
 * 补0
 * @param {type} num
 * @param {type} n
 * @returns {String}
 */
function pad(num, n) {
    return num + Array(n > num ? n - ("" + num).length + 1 : 0).join(0);
}
/**
 * number_format
 * @param number 传进来的数,
 * @param decimals 保留的小数位,默认保留两位小数,
 * @param dec_point 小数点符号
 * @param thousands_sep 为整数位每3位间隔符号
 */
function number_format(number, decimals, dec_point, thousands_sep) {
        var gapnum = 3;
    var str = "";

    number = number.toFixed(decimals); //格式化
    is_negative = number < 0 ? true : false;
    if (is_negative) {
        number = Math.abs(number) + "";
    }
    realnum = number.split(".")[0]; //整数位(使用小数点分割整数和小数部分)
    decimal = number.split(".")[1]; //小数位
    realnumarr = realnum.split(""); //将整数位逐位放进数组 ["1", "2", "3", "4", "5", "6"]

    //把整数部分从右往左拼接，每gapnum位添加一个thousands_sep符号
    for (var i = 1; i <= realnumarr.length; i++) {
        str = realnumarr[realnumarr.length - i] + str;
        if (i % gapnum == 0) {
            str = thousands_sep + str; //每隔gapnum位前面加指定符号
        }
    }

    //当遇到 gapnum 的倍数的时候，会出现比如 ",123",这种情况，所以要去掉最前面的 thousands_sep
    str = realnum.length % gapnum == 0 ? str.substr(1) : str;
    //重新拼接实数部分和小数位
    realnum = str + (decimals ? "" + dec_point + "" + (decimal ? pad(decimal, decimals) : pad(0, decimals)) : "");
    if (is_negative) {
        realnum = "-" + realnum;
    }
    return realnum;
}

//浮点数加法运算
function FloatAdd(arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

//浮点数减法运算
function FloatSub(arg1, arg2, decimal) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    //动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    if (decimal) {
        n = decimal;
    }
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//浮点数乘法运算
function FloatMul(arg1, arg2, decimal) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {}
    try {
        m += s2.split(".")[1].length;
    } catch (e) {}
    if (decimal) {
        return ((Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m)).toFixed(decimal);
    }
    return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
}

//浮点数除法运算
function FloatDiv(arg1, arg2, decimal) {
    var t1 = 0,
        t2 = 0,
        r1,
        r2;
    try {
        t1 = arg1.toString().split(".")[1].length;
    } catch (e) {}
    try {
        t2 = arg2.toString().split(".")[1].length;
    } catch (e) {}
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        if (decimal) {
            return Number((r1 / r2) * pow(10, t2 - t1)).toFixed(decimal);
        }
        return (r1 / r2) * pow(10, t2 - t1);
    }
}
/**
 * 价格格式
 * @param float|string $price
 * @param integer $decimal 默认2位
 * @return float
 */
function price_format(price, decimal = 2) {
    result = price.toFixed(decimal);
    return Number(result);
}
/**
 * 前台使用
 * 基准货币与其他货币之间的转换
 * @param type $price
 * @param type $tobase 是否转为基准货币
 * @return type
 */
function currencyExchange(price, currency, decimal_num) {
    var rate = currency.exchange_rate;
    var decimal = currency.decimal_num; //小数点问题
    if (decimal_num) {
        decimal = decimal_num;
    }
    return price_format(price * rate, decimal);
}

// 货币格式化
function formatMoney(number, currency, exchangeRate, appendSymbol,isFormat) {
    var exchangeRate = exchangeRate || currency.exchange_rate;
    var symbolLeft = currency.symbol_left;
    var symbolRigth = currency.symbol_right;
    var currencyFormat = currency.currency_format;
    var decimalNum = currency.decimal_num;

    var decimalSeparator = ".";
    var thousandsSeparator = "'";
    switch (currencyFormat) {
        case "123,456.78":
            decimalSeparator = ".";
            thousandsSeparator = ",";
            break;
        case "123,456":
            decimalSeparator = "";
            thousandsSeparator = ",";
            decimalNum = 0;
            break;
        case "123.456,78":
            decimalSeparator = ",";
            thousandsSeparator = ".";
            break;
        case "123.456":
            decimalSeparator = "";
            thousandsSeparator = ".";
            decimalNum = 0;
            break;
        case "123'456.65":
        default:
            decimalSeparator = ".";
            thousandsSeparator = "'";
            break;
    }
    number = number || 0;
    number = price_format(number * exchangeRate, decimalNum);

    if (isFormat === false) {
        return number
    }

    symbolLeft = symbolLeft != "" ? symbolLeft + " " : "";
    symbolRigth = symbolRigth != "" ? " " + symbolRigth : "";

    if (appendSymbol === false) {
        return number_format(number, decimalNum, decimalSeparator, thousandsSeparator);
    }

    return symbolLeft + "" + number_format(number, decimalNum, decimalSeparator, thousandsSeparator) + "" + symbolRigth;
}

/* 获取购物车数量 */
var isGetCartNumber = false;
function addCartNum() {
    if(!isGetCartNumber){
        var num = oemcart_cart_number.item_number
        moi.changeCartNumber(num);
        isGetCartNumber = true;
    }else{
    moi.ajax({
        url: "/cart.json",
        type: "GET",
        dataType: "json",
        success: function (res) {
            var num = res.data.item_number;
            moi.changeCartNumber(num);
        }
    });
    }
}
function miniCart() {
    $(".minicart_form").remove();
    $.ajax({
        url: "/cart/mini",
        cache: false,
        dataType: "html",
        success: function (html) {
            $(".minicart_mid").html(html);
            moi.onEvent("miniCart");
            if(window["oemcart_current_template"] !== "cart_list"){
                oemcartTriggerCartChange();
            }
        },
        beforeSend: function () {
            $(".minicart_top").after(
                '<div class="minicart_ajaxloading"><svg t="1592222422836" class="order_btn_icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6126"><path d="M512.606821 958.898283c-246.319012 0-446.698738-200.379727-446.698738-446.698738S266.287809 65.479317 512.606821 65.479317c17.73185 0 32.117488 14.385639 32.117488 32.117488s-14.385639 32.117488-32.117488 32.117488c-210.897268 0-382.463762 171.58696-382.463762 382.484228s171.566494 382.463762 382.463762 382.463762 382.484228-171.566494 382.484228-382.463762c0-106.013499-42.384319-204.603935-119.332852-277.558503-12.859889-12.211113-13.403265-32.536021-1.212618-45.416376 12.190647-12.901845 32.536021-13.403265 45.416376-1.212618 89.870844 85.229127 139.365094 200.35926 139.365094 324.187497C959.327048 758.518556 758.925832 958.898283 512.606821 958.898283z" p-id="6127"></path></svg></div>'
            );
        },
        complete: function () {
            $(".minicart_ajaxloading").remove();
        }
    });
}
function createAjaxLoading() {
    $("body").append(
        '<div class="ajaxloading"><svg t="1592222422836" class="order_btn_icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6126"><path d="M512.606821 958.898283c-246.319012 0-446.698738-200.379727-446.698738-446.698738S266.287809 65.479317 512.606821 65.479317c17.73185 0 32.117488 14.385639 32.117488 32.117488s-14.385639 32.117488-32.117488 32.117488c-210.897268 0-382.463762 171.58696-382.463762 382.484228s171.566494 382.463762 382.463762 382.463762 382.484228-171.566494 382.484228-382.463762c0-106.013499-42.384319-204.603935-119.332852-277.558503-12.859889-12.211113-13.403265-32.536021-1.212618-45.416376 12.190647-12.901845 32.536021-13.403265 45.416376-1.212618 89.870844 85.229127 139.365094 200.35926 139.365094 324.187497C959.327048 758.518556 758.925832 958.898283 512.606821 958.898283z" p-id="6127"></path></svg></div>'
    );
}
function removeAjaxLoading() {
    $(".ajaxloading").remove();
}

/**
 * @description: 相加
 * @return {*}
 */
Number.prototype.plus = function (arg) {
    var arg1 = this;
    var arg2 = arg;
    var r1, r2, m, c;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if (c > 0) {
        var cm = Math.pow(10, c);
        if (r1 > r2) {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        } else {
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    } else {
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
};
/**
 * @description: 相减
 * @return {*}
 */
Number.prototype.minus = function (arg) {
    var arg1 = this;
    var arg2 = arg;
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
    n = r1 >= r2 ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
};

/**
 * @description: 相乘
 * @return {*}
 */
Number.prototype.times = function (arg) {
    var arg1 = this;
    var arg2 = arg;
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {}
    try {
        m += s2.split(".")[1].length;
    } catch (e) {}
    return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
};

/**
 * @description: 相除
 * @return {*}
 */
Number.prototype.modulo = function (arg) {
    var arg1 = this;
    var arg2 = arg;
    var t1 = 0,
        t2 = 0,
        r1,
        r2;
    try {
        t1 = arg1.toString().split(".")[1].length;
    } catch (e) {}
    try {
        t2 = arg2.toString().split(".")[1].length;
    } catch (e) {}
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * pow(10, t2 - t1);
    }
};

(function () {
    setTimeout(() => {
        const targetApp = moi.getUrlParam("clearAppResponseCache");
        if (/* 配合应用后台删除对应的缓存 */ targetApp) {
            let countDown = 5;
            $("html").html(
                `
                <style>body>:not(.clear-app-response-cache-tip){display: none !important;}</style>
                <h2 class="clear-app-response-cache-tip" style="padding: 24px; text-align: center">已删除相关缓存，<span>${countDown}</span> 秒后自动关闭该窗口...</h2>
             `
            );
            setInterval(() => {
                $("h2 span").html(--countDown);
                if (countDown === 0) window.close();
            }, 1000);

            const storageKeys = Object.keys(localStorage);
            storageKeys.forEach((key) => {
                if (key.indexOf(`APP_RESPONSE_${targetApp}`) === 0) {
                    localStorage.removeItem(key);
                }
            });
        }
    });
})();


//邮箱后缀填充
function emailAutoFill(renderNode,inputNode) {
    let countryId = null
    let emailList = {global_email:[],local_email: []}
    let renderWrap = $(renderNode)
    for (let value of Object.values(oemcart_countrys)) {
        if(value.country_code_2 == oemcart_client_country) {
            countryId = value.id
            break
        }
    }
    if (countryId == null) return

    moi.ajax({
        url: `/country/hotemail/${countryId}`,
        success: function(res) {
            if(Array.isArray(res.data)) return
            emailList = res.data
            if(emailList.global_email) {
                emailList.global_email = emailList.global_email.map(item => '@' + item)
            }
            if(emailList.local_email) {
                emailList.local_email = emailList.local_email.map(item => '@' + item)
            }
        }
    })

    renderWrap.append('<div class="email_auto_fill_box"></div>')
    renderWrap.find(inputNode).on('focus', function() {
        templateRender($(this).val())
    })
    renderWrap.find(inputNode).on('blur', function() {
        renderWrap.find('.email_auto_fill_box').html('')
    })

    renderWrap.find(inputNode).on('input', function() {
        templateRender($(this).val())
    })

    function templateRender(str='') {
        if(str == '') {
            renderWrap.find('.email_auto_fill_box').html('')
            return
        }
        let resultData = {global_email:[],local_email: []}
        let strVerify = str.indexOf('@')
        
        if(strVerify !== -1) {
            let resultStr = str.substring(str.indexOf('@'),str.length)
            resultData.global_email = emailList.global_email.filter(item => item.includes(resultStr))
            resultData.local_email = emailList.local_email.filter(item => item.includes(resultStr))
        }else {
            resultData = emailList
        }
        if(resultData.global_email.length === 0 && resultData.local_email.length === 0) {
            renderWrap.find('.email_auto_fill_box').html('')
            return
        }
        let email_li = (list) => {
            let html = ''
            let prefix = strVerify != -1 ? str.substring(0,strVerify) : str
            list.forEach(item => {
                html += `<li>${prefix + item}</li>`
            })
            return html
        }
        
        let emailTemplate = `
            <ul class="global_email" style="margin:0px 12px;">
                ${email_li(resultData.global_email)}
            </ul>
            ${ resultData.global_email.length !== 0 && resultData.local_email.length !== 0 ? '<div class="divide" style="margin:0px 12px;"></div>' : ''}
            <ul class="local_email" style="margin:0px 12px;">
                ${email_li(resultData.local_email)}
            </ul>
        `;
        renderWrap.find('.email_auto_fill_box').html(emailTemplate)
        renderWrap.find('.email_auto_fill_box li').on('mousedown',function(e) {
            e.preventDefault()
            renderWrap.find(inputNode).val($(this).text())
            window['checkout_user_concat_init'] && window['checkout_user_concat_init']($(this).text())
            renderWrap.find(inputNode).removeClass('top-border')
            renderWrap.find('p.tip').remove()
            renderWrap.find('.email_auto_fill_box').html('')
        })
    }

}

// 购物车价格变化触发
function oemcartTriggerCartChange(){


    if(window["oemcart_current_template"] === "cart_list"){
        moi.onEvent("cartPriceChange", {
            total_price:formatMoney(oemcart_cart.total_price,oemcart_currency,'',false,false)
        })
        return
    }
    if(window["oemcart_current_template"] === "orderonepage_index" && oldPriceData){
        moi.onEvent("cartPriceChange", {
            total_price:formatMoney(oldPriceData.total_price || oemcart_cart.order ? oemcart_cart.order.total_price : oemcart_cart.total_price,oemcart_order_currency,'',false,false)
        })
        return
    }


    if(window["oemcart_current_template"] === "order_contact_information"){
        moi.onEvent("cartPriceChange", {
            total_price:formatMoney(oemcart_cart.total_price,oemcart_cart.currency,'',false,false)
        })
        return
    }

    if(window["oemcart_current_template"] === "order_shipping_method"){
        shippingCatTotalPrice(window['totalprice'])
        return
    }

    if(window["oemcart_current_template"] === "order_payment_method"){
        paymentCatTotalPrice(window['totalprice'])
        return
    }

    if(window["oemcart_current_template"] === "order_payment_gateway" || window["oemcart_current_template"] === "order_payment_abgateway"){
        moi.onEvent("cartPriceChange", {
            total_price:formatMoney(oemcart_cart.total_price_currency,oemcart_cart.currency,1,false,false)
        })
        return
    }



    const miniCart = moi.getPageStorage('miniCartInfo',false);
    if(miniCart){
        moi.onEvent("cartPriceChange", {
            total_price:formatMoney(miniCart.total_price,oemcart_currency,'',false,false)
        })
    }
}


//订单历史tag记录
function oemcartOrderTagHistory(tagName){
    const tags = JSON.parse(moi.getCookie("order_tag_history") || '[]');
    const index = tags.findIndex(tag=>tag.tag_name == tagName);
    const currentTime = new Date().getTime();
    if(index === -1){
        tags.unshift({
            tag_name:tagName,
            source_device:window["oemcart_site_type"] || "",
            create_time:currentTime,
            expire_time: currentTime + 30 * 86400,
        })
    }else{
        tags[index].create_time = currentTime;
        tags[index].expire_time = currentTime + 30 * 86400;
    }
    tags.sort((a,b)=>b.create_time - a.create_time);
    moi.setCookie("order_tag_history",JSON.stringify(tags),'d30')
}



 // this.isSupportIntersectionObserver = window['IntersectionObserver']?true:false;
        
        // const _that = this;
        // if(_that.isSupportIntersectionObserver){
        //     _that.observer = new IntersectionObserver(
        //         function (entrys) {
        //             for (const entry of entrys) {
        //                 console.log(entry.intersectionRatio);
        //                 if (entry.intersectionRatio >= 1) {
        //                     _that.handleTargetCallback($(entry.target))
        //                 }
        //             }
        //         },
        //         { rootMargin: "0px 0px 0px 0px" }
        //     )
        // }else{
        //     console.log("Not Supported IntersectionObserver")
        // }

        // 监听器 处理observer 不兼容使用scroll
    // Exposure.prototype.listener = function(target){
    //     if(!target){
    //         return false
    //     }
    //     const _that = this;
    //     target.find(_that.elementsAttr).each(function(){
    //         _that.observer.observe(this)
    //     })
    // }


//商品曝光加载
// (function(){

//     function Exposure(){
//         this.nodes = [];
//         // 上报数据队列
//         this.list = [];
//         // 需要处理的元素属性标识
//         this.elementsAttr = "product-exposure";
        
//         // 上报间隔时间
//         this.reportTime = 500
       
//     };

//     function isElementVisible(element) {
//         if (!element) return false;
    
//         var style = window.getComputedStyle(element);
//         if (style.display === 'none') return false;
//         if (style.visibility !== 'visible') return false;
//         if (style.opacity === '0') return false;
    
//         var rect = element.getBoundingClientRect();
//         if (rect.width <= 0 || rect.height <= 0) return false;
    
//         var parent = element.parentElement;
//         while (parent) {
//             var parentStyle = window.getComputedStyle(parent);
//             if (parentStyle.display === 'none') return false;
//             if (parentStyle.visibility !== 'visible') return false;
//             if (parentStyle.opacity === '0') return false;
//             if (parentStyle.overflow === 'hidden') {
//                 var parentRect = parent.getBoundingClientRect();
//                 if (rect.top < parentRect.top || rect.bottom > parentRect.bottom ||
//                     rect.left < parentRect.left || rect.right > parentRect.right) {
//                     return false;
//                 }
//             }
//             parent = parent.parentElement;
//         }
    
//         return true;
//     }
    
//     // 追加需要处理的节点
//     Exposure.prototype.listener = function(target){
//         if(!target){
//             return false
//         }
//         const _that = this;
//         target.find('['+_that.elementsAttr+']').each(function(){
//             _that.nodes.push($(this))
//         })
//         window.onscroll = moi.debounce(function(){
//             _that.handleScrollCallback()
//         },300) 
//     }
//     // 处理Scroll
//     Exposure.prototype.handleScrollCallback = function(){
//         const nodes = this.nodes;
//         const _that = this;
//         if (nodes.length > 0) {
//             const delIndexs = [];
//             for (let i = 0; i < nodes.length; i++) {
//                 _that.handleTargetCallback(nodes[i],function(){
//                     delIndexs.push(i)
//                 })
//             }
//         }
//     }

//     // 是否曝光
//     Exposure.prototype.isExposure = function(jqTarget){

//         if(jqTarget.attr("is-exposure") || !isElementVisible(jqTarget[0])){
//             return false
//         }

//         const $window = $(window);
//         const scrollTop = $window.scrollTop();
//         const wheight = $window.height();
//         const h = jqTarget.height();
//         const targetOffsetH = jqTarget.offset().top;
        
//         //元素距离
//         const screenMinH = scrollTop - parseInt(h * (1/2)); //元素1/2的最小高度
//         const screenMaxH = scrollTop + wheight - parseInt(h * (1/2)); //元素1/2的最大高度
//         if (targetOffsetH >  screenMinH && targetOffsetH < screenMaxH && jqTarget.is(":visible")) {
//             return true
//         }
//         return false
//     }

//     // 获取节点数据
//     Exposure.prototype.getTargetAttr = function(jqTarget){
//        const ec_data = JSON.parse(decodeURIComponent(jqTarget.attr("data-product-ec-info") || "{}"));
//        const hit_type_category = jqTarget.attr("data-product-ec-list-name");
//        const hit_type_value = jqTarget.attr("data-product-ec-list-position");
//        return {ec_data,hit_type_category,hit_type_value}
//     }

    
//     Exposure.prototype.getMetaContent = function (metaName) {
//         const metas = document.getElementsByTagName("meta");
//         for (let i = 0; i < metas.length; i++) {
//             if (metas[i].getAttribute("name") === metaName) {
//                 return metas[i].getAttribute("content");
//             }
//         }
//         return "";
//     };
//     // 组装数据
//     Exposure.prototype.mergeCollectData = function(data){
//         return {
//             pv_id: window.oemcart_pv_id || "",
//             store_id: window.oemcart_store_id || "",
//             document_location_url: encodeURIComponent(window.location.href),
//             document_location_title: document.title,
//             meta_keywords: this.getMetaContent("keywords"),
//             prev_url: document.referrer,
//             data_from: moi.getUrlParam("data_from") || oemcart_data_from,
//             vid: window.oemcart_global_unique_id || "",
//             rnd: Math.random(),
//             "hit_type":"event",
//             'hit_type_name': 'add_impression',
//             'hit_type_category': data.hit_type_category,
//             'hit_type_label': data.ec_data && data.ec_data.title || "",
//             'hit_type_action': '',
//             'hit_type_value': data.hit_type_value,
//             'hit_type_id': data.ec_data && data.ec_data.ec_data_id || "",
//             'ec_data': encodeURIComponent(JSON.stringify(data.ec_data))
//         }
//     }

//     // 数据上报
//     Exposure.prototype.collectReport = function(jqTarget,callback){
//         if(this.list.length){
//             const exitData = this.list.splice(0,50);
//             fetch("/homeapi/collect?type=batch", {
//                 method: "POST",
//                 headers: {
//                     "Content-Type": "application/json"
//                 },
//                 body: JSON.stringify(exitData),
//                 keepalive:true
//             });
//         }
//     }

    
//     //处理节点数据追加上报数据
//     Exposure.prototype.handleTargetCallback = function(jqTarget,callback){
//         if(this.isExposure(jqTarget)){
//             jqTarget.attr("is-exposure",'true');
//             jqTarget.removeAttr(this.elementsAttr);
//             const attrData = this.getTargetAttr(jqTarget);
//             this.list.push( this.mergeCollectData(attrData));
//             callback && callback()
//         }
//     }

//     // 初始化
//     Exposure.prototype.init = function(option){
//         const _that = this;
//         option && Object.assign(this,option)

//         document.addEventListener("DOMContentLoaded",function(){
//             _that.listener($('html,body'));

//             setInterval(function(){
//                 _that.collectReport()
//             },_that.reportTime)
//         })
//         // 未添加的元素监听img 加载
//         document.addEventListener('DOMNodeInserted', function (event) {
//             _that.listener($(event.target))
//         }, false);
//     }

//     window['oemcartExposure'] = new Exposure();

//     if(moi.getCookie('is_theme_edit') != '1'){
//         window['oemcartExposure'].init()
//     }

// })()
//todo 解压数据
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).pako={})}(this,(function(t){"use strict";function e(t){let e=t.length;for(;--e>=0;)t[e]=0}const a=256,i=286,n=30,s=15,r=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),o=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),l=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),d=new Array(576);e(d);const _=new Array(60);e(_);const f=new Array(512);e(f);const c=new Array(256);e(c);const u=new Array(29);e(u);const w=new Array(n);function m(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}let b,g,p;function k(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}e(w);const v=t=>t<256?f[t]:f[256+(t>>>7)],y=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},x=(t,e,a)=>{t.bi_valid>16-a?(t.bi_buf|=e<<t.bi_valid&65535,y(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=a)},z=(t,e,a)=>{x(t,a[2*e],a[2*e+1])},A=(t,e)=>{let a=0;do{a|=1&t,t>>>=1,a<<=1}while(--e>0);return a>>>1},E=(t,e,a)=>{const i=new Array(16);let n,r,o=0;for(n=1;n<=s;n++)o=o+a[n-1]<<1,i[n]=o;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=A(i[e]++,e))}},R=t=>{let e;for(e=0;e<i;e++)t.dyn_ltree[2*e]=0;for(e=0;e<n;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},Z=t=>{t.bi_valid>8?y(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},U=(t,e,a,i)=>{const n=2*e,s=2*a;return t[n]<t[s]||t[n]===t[s]&&i[e]<=i[a]},S=(t,e,a)=>{const i=t.heap[a];let n=a<<1;for(;n<=t.heap_len&&(n<t.heap_len&&U(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!U(e,i,t.heap[n],t.depth));)t.heap[a]=t.heap[n],a=n,n<<=1;t.heap[a]=i},D=(t,e,i)=>{let n,s,l,h,d=0;if(0!==t.sym_next)do{n=255&t.pending_buf[t.sym_buf+d++],n+=(255&t.pending_buf[t.sym_buf+d++])<<8,s=t.pending_buf[t.sym_buf+d++],0===n?z(t,s,e):(l=c[s],z(t,l+a+1,e),h=r[l],0!==h&&(s-=u[l],x(t,s,h)),n--,l=v(n),z(t,l,i),h=o[l],0!==h&&(n-=w[l],x(t,n,h)))}while(d<t.sym_next);z(t,256,e)},T=(t,e)=>{const a=e.dyn_tree,i=e.stat_desc.static_tree,n=e.stat_desc.has_stree,r=e.stat_desc.elems;let o,l,h,d=-1;for(t.heap_len=0,t.heap_max=573,o=0;o<r;o++)0!==a[2*o]?(t.heap[++t.heap_len]=d=o,t.depth[o]=0):a[2*o+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=d<2?++d:0,a[2*h]=1,t.depth[h]=0,t.opt_len--,n&&(t.static_len-=i[2*h+1]);for(e.max_code=d,o=t.heap_len>>1;o>=1;o--)S(t,a,o);h=r;do{o=t.heap[1],t.heap[1]=t.heap[t.heap_len--],S(t,a,1),l=t.heap[1],t.heap[--t.heap_max]=o,t.heap[--t.heap_max]=l,a[2*h]=a[2*o]+a[2*l],t.depth[h]=(t.depth[o]>=t.depth[l]?t.depth[o]:t.depth[l])+1,a[2*o+1]=a[2*l+1]=h,t.heap[1]=h++,S(t,a,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,r=e.stat_desc.has_stree,o=e.stat_desc.extra_bits,l=e.stat_desc.extra_base,h=e.stat_desc.max_length;let d,_,f,c,u,w,m=0;for(c=0;c<=s;c++)t.bl_count[c]=0;for(a[2*t.heap[t.heap_max]+1]=0,d=t.heap_max+1;d<573;d++)_=t.heap[d],c=a[2*a[2*_+1]+1]+1,c>h&&(c=h,m++),a[2*_+1]=c,_>i||(t.bl_count[c]++,u=0,_>=l&&(u=o[_-l]),w=a[2*_],t.opt_len+=w*(c+u),r&&(t.static_len+=w*(n[2*_+1]+u)));if(0!==m){do{for(c=h-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[h]--,m-=2}while(m>0);for(c=h;0!==c;c--)for(_=t.bl_count[c];0!==_;)f=t.heap[--d],f>i||(a[2*f+1]!==c&&(t.opt_len+=(c-a[2*f+1])*a[2*f],a[2*f+1]=c),_--)}})(t,e),E(a,d,t.bl_count)},O=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++)n=r,r=e[2*(i+1)+1],++o<l&&n===r||(o<h?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4))},I=(t,e,a)=>{let i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),i=0;i<=a;i++)if(n=r,r=e[2*(i+1)+1],!(++o<l&&n===r)){if(o<h)do{z(t,n,t.bl_tree)}while(0!=--o);else 0!==n?(n!==s&&(z(t,n,t.bl_tree),o--),z(t,16,t.bl_tree),x(t,o-3,2)):o<=10?(z(t,17,t.bl_tree),x(t,o-3,3)):(z(t,18,t.bl_tree),x(t,o-11,7));o=0,s=n,0===r?(l=138,h=3):n===r?(l=6,h=3):(l=7,h=4)}};let F=!1;const L=(t,e,a,i)=>{x(t,0+(i?1:0),3),Z(t),y(t,a),y(t,~a),a&&t.pending_buf.set(t.window.subarray(e,e+a),t.pending),t.pending+=a};var N=(t,e,i,n)=>{let s,r,o=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<a;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),T(t,t.l_desc),T(t,t.d_desc),o=(t=>{let e;for(O(t,t.dyn_ltree,t.l_desc.max_code),O(t,t.dyn_dtree,t.d_desc.max_code),T(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*h[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?L(t,e,i,n):4===t.strategy||r===s?(x(t,2+(n?1:0),3),D(t,d,_)):(x(t,4+(n?1:0),3),((t,e,a,i)=>{let n;for(x(t,e-257,5),x(t,a-1,5),x(t,i-4,4),n=0;n<i;n++)x(t,t.bl_tree[2*h[n]+1],3);I(t,t.dyn_ltree,e-1),I(t,t.dyn_dtree,a-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),D(t,t.dyn_ltree,t.dyn_dtree)),R(t),n&&Z(t)},B={_tr_init:t=>{F||((()=>{let t,e,a,h,k;const v=new Array(16);for(a=0,h=0;h<28;h++)for(u[h]=a,t=0;t<1<<r[h];t++)c[a++]=h;for(c[a-1]=h,k=0,h=0;h<16;h++)for(w[h]=k,t=0;t<1<<o[h];t++)f[k++]=h;for(k>>=7;h<n;h++)for(w[h]=k<<7,t=0;t<1<<o[h]-7;t++)f[256+k++]=h;for(e=0;e<=s;e++)v[e]=0;for(t=0;t<=143;)d[2*t+1]=8,t++,v[8]++;for(;t<=255;)d[2*t+1]=9,t++,v[9]++;for(;t<=279;)d[2*t+1]=7,t++,v[7]++;for(;t<=287;)d[2*t+1]=8,t++,v[8]++;for(E(d,287,v),t=0;t<n;t++)_[2*t+1]=5,_[2*t]=A(t,5);b=new m(d,r,257,i,s),g=new m(_,o,0,n,s),p=new m(new Array(0),l,0,19,7)})(),F=!0),t.l_desc=new k(t.dyn_ltree,b),t.d_desc=new k(t.dyn_dtree,g),t.bl_desc=new k(t.bl_tree,p),t.bi_buf=0,t.bi_valid=0,R(t)},_tr_stored_block:L,_tr_flush_block:N,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(c[i]+a+1)]++,t.dyn_dtree[2*v(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{x(t,2,3),z(t,256,d),(t=>{16===t.bi_valid?(y(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var C=(t,e,a,i)=>{let n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0}while(--r);n%=65521,s%=65521}return n|s<<16|0};const M=new Uint32Array((()=>{let t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[a]=t}return e})());var H=(t,e,a,i)=>{const n=M,s=i+a;t^=-1;for(let a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t},j={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:P,_tr_stored_block:Y,_tr_flush_block:G,_tr_tally:X,_tr_align:W}=B,{Z_NO_FLUSH:q,Z_PARTIAL_FLUSH:J,Z_FULL_FLUSH:Q,Z_FINISH:V,Z_BLOCK:$,Z_OK:tt,Z_STREAM_END:et,Z_STREAM_ERROR:at,Z_DATA_ERROR:it,Z_BUF_ERROR:nt,Z_DEFAULT_COMPRESSION:st,Z_FILTERED:rt,Z_HUFFMAN_ONLY:ot,Z_RLE:lt,Z_FIXED:ht,Z_DEFAULT_STRATEGY:dt,Z_UNKNOWN:_t,Z_DEFLATED:ft}=K,ct=258,ut=262,wt=42,mt=113,bt=666,gt=(t,e)=>(t.msg=j[e],e),pt=t=>2*t-(t>4?9:0),kt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},vt=t=>{let e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0}while(--e)};let yt=(t,e,a)=>(e<<t.hash_shift^a)&t.hash_mask;const xt=t=>{const e=t.state;let a=e.pending;a>t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0))},zt=(t,e)=>{G(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,xt(t.strm)},At=(t,e)=>{t.pending_buf[t.pending++]=e},Et=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},Rt=(t,e,a,i)=>{let n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=C(t.adler,e,n,a):2===t.state.wrap&&(t.adler=H(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n)},Zt=(t,e)=>{let a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;const l=t.strstart>t.w_size-ut?t.strstart-(t.w_size-ut):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+ct;let c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&s<f);if(i=ct-(f-s),s=f-ct,i>r){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r]}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead},Ut=t=>{const e=t.w_size;let a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ut)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),vt(t),i+=e),0===t.strm.avail_in)break;if(a=Rt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=yt(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=yt(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<ut&&0!==t.strm.avail_in)},St=(t,e)=>{let a,i,n,s=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_out<n)break;if(n=t.strm.avail_out-n,i=t.strstart-t.block_start,a>i+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a<s&&(0===a&&e!==V||e===q||a!==i+t.strm.avail_in))break;r=e===V&&a===i+t.strm.avail_in?1:0,Y(t,0,0,r),t.pending_buf[t.pending-4]=a,t.pending_buf[t.pending-3]=a>>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,xt(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(Rt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a)}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),r?4:e!==q&&e!==V&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(n=t.window_size-t.strstart,t.strm.avail_in>n&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(Rt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water<t.strstart&&(t.high_water=t.strstart),n=t.bi_valid+42>>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===V)&&e!==q&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===V&&0===t.strm.avail_in&&a===i?1:0,Y(t,t.block_start,a,r),t.block_start+=a,xt(t.strm)),r?3:1)},Dt=(t,e)=>{let a,i;for(;;){if(t.lookahead<ut){if(Ut(t),t.lookahead<ut&&e===q)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-ut&&(t.match_length=Zt(t,a)),t.match_length>=3)if(i=X(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=yt(t,t.ins_h,t.window[t.strstart+1]);else i=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(zt(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2},Tt=(t,e)=>{let a,i,n;for(;;){if(t.lookahead<ut){if(Ut(t),t.lookahead<ut&&e===q)return 1;if(0===t.lookahead)break}if(a=0,t.lookahead>=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length<t.max_lazy_match&&t.strstart-a<=t.w_size-ut&&(t.match_length=Zt(t,a),t.match_length<=5&&(t.strategy===rt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=X(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(zt(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(i=X(t,0,t.window[t.strstart-1]),i&&zt(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(i=X(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2};function Ot(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n}const It=[new Ot(0,0,0,0,St),new Ot(4,4,8,4,Dt),new Ot(4,5,16,8,Dt),new Ot(4,6,32,32,Dt),new Ot(4,4,16,16,Tt),new Ot(8,16,32,32,Tt),new Ot(8,16,128,128,Tt),new Ot(8,32,128,256,Tt),new Ot(32,128,258,1024,Tt),new Ot(32,258,258,4096,Tt)];function Ft(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ft,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),kt(this.dyn_ltree),kt(this.dyn_dtree),kt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),kt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),kt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Lt=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==wt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==mt&&e.status!==bt?1:0},Nt=t=>{if(Lt(t))return gt(t,at);t.total_in=t.total_out=0,t.data_type=_t;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?wt:mt,t.adler=2===e.wrap?0:1,e.last_flush=-2,P(e),tt},Bt=t=>{const e=Nt(t);var a;return e===tt&&((a=t.state).window_size=2*a.w_size,kt(a.head),a.max_lazy_match=It[a.level].max_lazy,a.good_match=It[a.level].good_length,a.nice_match=It[a.level].nice_length,a.max_chain_length=It[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e},Ct=(t,e,a,i,n,s)=>{if(!t)return at;let r=1;if(e===st&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ft||i<8||i>15||e<0||e>9||s<0||s>ht||8===i&&1!==r)return gt(t,at);8===i&&(i=9);const o=new Ft;return t.state=o,o.strm=t,o.status=wt,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=a,Bt(t)};var Mt={deflateInit:(t,e)=>Ct(t,e,ft,15,8,dt),deflateInit2:Ct,deflateReset:Bt,deflateResetKeep:Nt,deflateSetHeader:(t,e)=>Lt(t)||2!==t.state.wrap?at:(t.state.gzhead=e,tt),deflate:(t,e)=>{if(Lt(t)||e>$||e<0)return t?gt(t,at):at;const a=t.state;if(!t.output||0!==t.avail_in&&!t.input||a.status===bt&&e!==V)return gt(t,0===t.avail_out?nt:at);const i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(xt(t),0===t.avail_out)return a.last_flush=-1,tt}else if(0===t.avail_in&&pt(e)<=pt(i)&&e!==V)return gt(t,nt);if(a.status===bt&&0!==t.avail_in)return gt(t,nt);if(a.status===wt&&0===a.wrap&&(a.status=mt),a.status===wt){let e=ft+(a.w_bits-8<<4)<<8,i=-1;if(i=a.strategy>=ot||a.level<2?0:a.level<6?1:6===a.level?2:3,e|=i<<6,0!==a.strstart&&(e|=32),e+=31-e%31,Et(a,e),0!==a.strstart&&(Et(a,t.adler>>>16),Et(a,65535&t.adler)),t.adler=1,a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt}if(57===a.status)if(t.adler=0,At(a,31),At(a,139),At(a,8),a.gzhead)At(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),At(a,255&a.gzhead.time),At(a,a.gzhead.time>>8&255),At(a,a.gzhead.time>>16&255),At(a,a.gzhead.time>>24&255),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(At(a,255&a.gzhead.extra.length),At(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=H(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(At(a,0),At(a,0),At(a,0),At(a,0),At(a,0),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,3),a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;if(69===a.status){if(a.gzhead.extra){let e=a.pending,i=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+i>a.pending_buf_size;){let n=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+n),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>e&&(t.adler=H(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex+=n,xt(t),0!==a.pending)return a.last_flush=-1,tt;e=0,i-=n}let n=new Uint8Array(a.gzhead.extra);a.pending_buf.set(n.subarray(a.gzindex,a.gzindex+i),a.pending),a.pending+=i,a.gzhead.hcrc&&a.pending>e&&(t.adler=H(t.adler,a.pending_buf,a.pending-e,e)),a.gzindex=0}a.status=73}if(73===a.status){if(a.gzhead.name){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=H(t.adler,a.pending_buf,a.pending-i,i)),xt(t),0!==a.pending)return a.last_flush=-1,tt;i=0}e=a.gzindex<a.gzhead.name.length?255&a.gzhead.name.charCodeAt(a.gzindex++):0,At(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=H(t.adler,a.pending_buf,a.pending-i,i)),a.gzindex=0}a.status=91}if(91===a.status){if(a.gzhead.comment){let e,i=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>i&&(t.adler=H(t.adler,a.pending_buf,a.pending-i,i)),xt(t),0!==a.pending)return a.last_flush=-1,tt;i=0}e=a.gzindex<a.gzhead.comment.length?255&a.gzhead.comment.charCodeAt(a.gzindex++):0,At(a,e)}while(0!==e);a.gzhead.hcrc&&a.pending>i&&(t.adler=H(t.adler,a.pending_buf,a.pending-i,i))}a.status=103}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(xt(t),0!==a.pending))return a.last_flush=-1,tt;At(a,255&t.adler),At(a,t.adler>>8&255),t.adler=0}if(a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt}if(0!==t.avail_in||0!==a.lookahead||e!==q&&a.status!==bt){let i=0===a.level?St(a,e):a.strategy===ot?((t,e)=>{let a;for(;;){if(0===t.lookahead&&(Ut(t),0===t.lookahead)){if(e===q)return 1;break}if(t.match_length=0,a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(zt(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2})(a,e):a.strategy===lt?((t,e)=>{let a,i,n,s;const r=t.window;for(;;){if(t.lookahead<=ct){if(Ut(t),t.lookahead<=ct&&e===q)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+ct;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&n<s);t.match_length=ct-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(a=X(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(zt(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2})(a,e):It[a.level].func(a,e);if(3!==i&&4!==i||(a.status=bt),1===i||3===i)return 0===t.avail_out&&(a.last_flush=-1),tt;if(2===i&&(e===J?W(a):e!==$&&(Y(a,0,0,!1),e===Q&&(kt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),xt(t),0===t.avail_out))return a.last_flush=-1,tt}return e!==V?tt:a.wrap<=0?et:(2===a.wrap?(At(a,255&t.adler),At(a,t.adler>>8&255),At(a,t.adler>>16&255),At(a,t.adler>>24&255),At(a,255&t.total_in),At(a,t.total_in>>8&255),At(a,t.total_in>>16&255),At(a,t.total_in>>24&255)):(Et(a,t.adler>>>16),Et(a,65535&t.adler)),xt(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?tt:et)},deflateEnd:t=>{if(Lt(t))return at;const e=t.state.status;return t.state=null,e===mt?gt(t,it):tt},deflateSetDictionary:(t,e)=>{let a=e.length;if(Lt(t))return at;const i=t.state,n=i.wrap;if(2===n||1===n&&i.status!==wt||i.lookahead)return at;if(1===n&&(t.adler=C(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(kt(i.head),i.strstart=0,i.block_start=0,i.insert=0);let t=new Uint8Array(i.w_size);t.set(e.subarray(a-i.w_size,a),0),e=t,a=i.w_size}const s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,Ut(i);i.lookahead>=3;){let t=i.strstart,e=i.lookahead-2;do{i.ins_h=yt(i,i.ins_h,i.window[t+3-1]),i.prev[t&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=t,t++}while(--e);i.strstart=t,i.lookahead=2,Ut(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,tt},deflateInfo:"pako deflate (from Nodeca project)"};const Ht=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var jt=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const a=e.shift();if(a){if("object"!=typeof a)throw new TypeError(a+"must be non-object");for(const e in a)Ht(a,e)&&(t[e]=a[e])}}return t},Kt=t=>{let e=0;for(let a=0,i=t.length;a<i;a++)e+=t[a].length;const a=new Uint8Array(e);for(let e=0,i=0,n=t.length;e<n;e++){let n=t[e];a.set(n,i),i+=n.length}return a};let Pt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Pt=!1}const Yt=new Uint8Array(256);for(let t=0;t<256;t++)Yt[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Yt[254]=Yt[254]=1;var Gt=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,a,i,n,s,r=t.length,o=0;for(n=0;n<r;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),o+=a<128?1:a<2048?2:a<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)a=t.charCodeAt(n),55296==(64512&a)&&n+1<r&&(i=t.charCodeAt(n+1),56320==(64512&i)&&(a=65536+(a-55296<<10)+(i-56320),n++)),a<128?e[s++]=a:a<2048?(e[s++]=192|a>>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);return e},Xt=(t,e)=>{const a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(t.subarray(0,e));let i,n;const s=new Array(2*a);for(n=0,i=0;i<a;){let e=t[i++];if(e<128){s[n++]=e;continue}let r=Yt[e];if(r>4)s[n++]=65533,i+=r-1;else{for(e&=2===r?31:3===r?15:7;r>1&&i<a;)e=e<<6|63&t[i++],r--;r>1?s[n++]=65533:e<65536?s[n++]=e:(e-=65536,s[n++]=55296|e>>10&1023,s[n++]=56320|1023&e)}}return((t,e)=>{if(e<65534&&t.subarray&&Pt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));let a="";for(let i=0;i<e;i++)a+=String.fromCharCode(t[i]);return a})(s,n)},Wt=(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let a=e-1;for(;a>=0&&128==(192&t[a]);)a--;return a<0||0===a?e:a+Yt[t[a]]>e?a:e};var qt=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Jt=Object.prototype.toString,{Z_NO_FLUSH:Qt,Z_SYNC_FLUSH:Vt,Z_FULL_FLUSH:$t,Z_FINISH:te,Z_OK:ee,Z_STREAM_END:ae,Z_DEFAULT_COMPRESSION:ie,Z_DEFAULT_STRATEGY:ne,Z_DEFLATED:se}=K;function re(t){this.options=jt({level:ie,method:se,chunkSize:16384,windowBits:15,memLevel:8,strategy:ne},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt,this.strm.avail_out=0;let a=Mt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==ee)throw new Error(j[a]);if(e.header&&Mt.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Gt(e.dictionary):"[object ArrayBuffer]"===Jt.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Mt.deflateSetDictionary(this.strm,t),a!==ee)throw new Error(j[a]);this._dict_set=!0}}function oe(t,e){const a=new re(e);if(a.push(t,!0),a.err)throw a.msg||j[a.err];return a.result}re.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize;let n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?te:Qt,"string"==typeof t?a.input=Gt(t):"[object ArrayBuffer]"===Jt.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;)if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===Vt||s===$t)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Mt.deflate(a,s),n===ae)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Mt.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===ee;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break}else this.onData(a.output)}return!0},re.prototype.onData=function(t){this.chunks.push(t)},re.prototype.onEnd=function(t){t===ee&&(this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var le={Deflate:re,deflate:oe,deflateRaw:function(t,e){return(e=e||{}).raw=!0,oe(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,oe(t,e)},constants:K};const he=16209;var de=function(t,e){let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;const E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<<E.lenbits)-1,b=(1<<E.distbits)-1;t:do{c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=u[f&m];e:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<<p)-1)];continue e}if(32&p){E.mode=16191;break t}t.msg="invalid literal/length code",E.mode=he;break t}k=65535&g,p&=15,p&&(c<p&&(f+=z[a++]<<c,c+=8),k+=f&(1<<p)-1,f>>>=p,c-=p),c<15&&(f+=z[a++]<<c,c+=8,f+=z[a++]<<c,c+=8),g=w[f&b];a:for(;;){if(p=g>>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<<p)-1)];continue a}t.msg="invalid distance code",E.mode=he;break t}if(v=65535&g,p&=15,c<p&&(f+=z[a++]<<c,c+=8,c<p&&(f+=z[a++]<<c,c+=8)),v+=f&(1<<p)-1,v>o){t.msg="invalid distance too far back",E.mode=he;break t}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=he;break t}if(y=0,x=_,0===d){if(y+=l-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}else if(d<p){if(y+=l+d-p,p-=d,p<k){k-=p;do{A[n++]=_[y++]}while(--p);if(y=0,d<k){p=d,k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}}}else if(y+=d-p,p<k){k-=p;do{A[n++]=_[y++]}while(--p);y=n-v,x=A}for(;k>2;)A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]))}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]))}break}}break}}while(a<i&&n<r);k=c>>3,a-=k,c-=k<<3,f&=(1<<c)-1,t.next_in=a,t.next_out=n,t.avail_in=a<i?i-a+5:5-(a-i),t.avail_out=n<r?r-n+257:257-(n-r),E.hold=f,E.bits=c};const _e=15,fe=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),ce=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),ue=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),we=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var me=(t,e,a,i,n,s,r,o)=>{const l=o.bits;let h,d,_,f,c,u,w=0,m=0,b=0,g=0,p=0,k=0,v=0,y=0,x=0,z=0,A=null;const E=new Uint16Array(16),R=new Uint16Array(16);let Z,U,S,D=null;for(w=0;w<=_e;w++)E[w]=0;for(m=0;m<i;m++)E[e[a+m]]++;for(p=l,g=_e;g>=1&&0===E[g];g--);if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b<g&&0===E[b];b++);for(p<b&&(p=b),y=1,w=1;w<=_e;w++)if(y<<=1,y-=E[w],y<0)return-1;if(y>0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<_e;w++)R[w+1]=R[w]+E[w];for(m=0;m<i;m++)0!==e[a+m]&&(r[R[e[a+m]]++]=m);if(0===t?(A=D=r,u=20):1===t?(A=fe,D=ce,u=257):(A=ue,D=we,u=0),z=0,m=0,w=b,c=s,k=p,v=0,_=-1,x=1<<p,f=x-1,1===t&&x>852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1<u?(U=0,S=r[m]):r[m]>=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<<w-v,d=1<<k,b=d;do{d-=h,n[c+(z>>v)+d]=Z<<24|U<<16|S|0}while(0!==d);for(h=1<<w-1;z&h;)h>>=1;if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]]}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<<k;k+v<g&&(y-=E[k+v],!(y<=0));)k++,y<<=1;if(x+=1<<k,1===t&&x>852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0};const{Z_FINISH:be,Z_BLOCK:ge,Z_TREES:pe,Z_OK:ke,Z_STREAM_END:ve,Z_NEED_DICT:ye,Z_STREAM_ERROR:xe,Z_DATA_ERROR:ze,Z_MEM_ERROR:Ae,Z_BUF_ERROR:Ee,Z_DEFLATED:Re}=K,Ze=16180,Ue=16190,Se=16191,De=16192,Te=16194,Oe=16199,Ie=16200,Fe=16206,Le=16209,Ne=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function Be(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Ce=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<Ze||e.mode>16211?1:0},Me=t=>{if(Ce(t))return xe;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=Ze,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ke},He=t=>{if(Ce(t))return xe;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,Me(t)},je=(t,e)=>{let a;if(Ce(t))return xe;const i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?xe:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,He(t))},Ke=(t,e)=>{if(!t)return xe;const a=new Be;t.state=a,a.strm=t,a.window=null,a.mode=Ze;const i=je(t,e);return i!==ke&&(t.state=null),i};let Pe,Ye,Ge=!0;const Xe=t=>{if(Ge){Pe=new Int32Array(512),Ye=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(me(1,t.lens,0,288,Pe,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;me(2,t.lens,0,32,Ye,0,t.work,{bits:5}),Ge=!1}t.lencode=Pe,t.lenbits=9,t.distcode=Ye,t.distbits=5},We=(t,e,a,i)=>{let n;const s=t.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0};var qe={inflateReset:He,inflateReset2:je,inflateResetKeep:Me,inflateInit:t=>Ke(t,15),inflateInit2:Ke,inflate:(t,e)=>{let a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z=0;const A=new Uint8Array(4);let E,R;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Ce(t)||!t.output||!t.input&&0!==t.avail_in)return xe;a=t.state,a.mode===Se&&(a.mode=De),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,_=o,f=l,x=ke;t:for(;;)switch(a.mode){case Ze:if(0===a.wrap){a.mode=De;break}for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(2&a.wrap&&35615===h){0===a.wbits&&(a.wbits=15),a.check=0,A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0),h=0,d=0,a.mode=16181;break}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=Le;break}if((15&h)!==Re){t.msg="unknown compression method",a.mode=Le;break}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=Le;break}a.dmax=1<<a.wbits,a.flags=0,t.adler=a.check=1,a.mode=512&h?16189:Se,h=0,d=0;break;case 16181:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.flags=h,(255&a.flags)!==Re){t.msg="unknown compression method",a.mode=Le;break}if(57344&a.flags){t.msg="unknown header flags set",a.mode=Le;break}a.head&&(a.head.text=h>>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.time=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=H(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.head&&(a.head.xflags=255&h,a.head.os=h>>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length=h,a.head&&(a.head.extra_len=h),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=H(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=H(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.name=null);a.length=0,a.mode=16187;case 16187:if(4096&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.comment+=String.fromCharCode(y))}while(y&&c<o);if(512&a.flags&&4&a.wrap&&(a.check=H(a.check,i,c,s)),o-=c,s+=c,y)break t}else a.head&&(a.head.comment=null);a.mode=16188;case 16188:if(512&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(65535&a.check)){t.msg="header crc mismatch",a.mode=Le;break}h=0,d=0}a.head&&(a.head.hcrc=a.flags>>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=Se;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}t.adler=a.check=Ne(h),h=0,d=0,a.mode=Ue;case Ue:if(0===a.havedict)return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,ye;t.adler=a.check=1,a.mode=Se;case Se:if(e===ge||e===pe)break t;case De:if(a.last){h>>>=7&d,d-=7&d,a.mode=Fe;break}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}switch(a.last=1&h,h>>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Xe(a),a.mode=Oe,e===pe){h>>>=2,d-=2;break t}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=Le}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if((65535&h)!=(h>>>16^65535)){t.msg="invalid stored block lengths",a.mode=Le;break}if(a.length=65535&h,h=0,d=0,a.mode=Te,e===pe)break t;case Te:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break}a.mode=Se;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(a.nlen=257+(31&h),h>>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=Le;break}a.have=0,a.mode=16197;case 16197:for(;a.have<a.ncode;){for(;d<3;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.lens[Z[a.have++]]=7&h,h>>>=3,d-=3}for(;a.have<19;)a.lens[Z[a.have++]]=0;if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=me(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=Le;break}a.have=0,a.mode=16198;case 16198:for(;a.have<a.nlen+a.ndist;){for(;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(g<16)h>>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(h>>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=Le;break}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2}else if(17===g){for(R=m+3;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3}else{for(R=m+7;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=Le;break}for(;c--;)a.lens[a.have++]=y}}if(a.mode===Le)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=Le;break}if(a.lenbits=9,E={bits:a.lenbits},x=me(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=Le;break}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=me(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=Le;break}if(a.mode=Oe,e===pe)break t;case Oe:a.mode=Ie;case Ie:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,de(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,a.mode===Se&&(a.back=-1);break}for(a.back=0;z=a.lencode[h&(1<<a.lenbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(b&&0==(240&b)){for(p=m,k=b,v=g;z=a.lencode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break}if(32&b){a.back=-1,a.mode=Se;break}if(64&b){t.msg="invalid literal/length code",a.mode=Le;break}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.length+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<<a.distbits)-1],m=z>>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(0==(240&b)){for(p=m,k=b,v=g;z=a.distcode[v+((h&(1<<p+k)-1)>>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}h>>>=p,d-=p,a.back+=p}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=Le;break}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d<R;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}a.offset+=h&(1<<a.extra)-1,h>>>=a.extra,d-=a.extra,a.back+=a.extra}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=Le;break}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=Le;break}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++]}while(--c);0===a.length&&(a.mode=Ie);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=Ie;break;case Fe:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<<d,d+=8}if(f-=l,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?H(a.check,n,f,r-f):C(a.check,n,f,r-f)),f=l,4&a.wrap&&(a.flags?h:Ne(h))!==a.check){t.msg="incorrect data check",a.mode=Le;break}h=0,d=0}a.mode=16207;case 16207:if(a.wrap&&a.flags){for(;d<32;){if(0===o)break t;o--,h+=i[s++]<<d,d+=8}if(4&a.wrap&&h!==(4294967295&a.total)){t.msg="incorrect length check",a.mode=Le;break}h=0,d=0}a.mode=16208;case 16208:x=ve;break t;case Le:x=ze;break t;case 16210:return Ae;default:return xe}return t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,(a.wsize||f!==t.avail_out&&a.mode<Le&&(a.mode<Fe||e!==be))&&We(t,t.output,t.next_out,f-t.avail_out),_-=t.avail_in,f-=t.avail_out,t.total_in+=_,t.total_out+=f,a.total+=f,4&a.wrap&&f&&(t.adler=a.check=a.flags?H(a.check,n,f,t.next_out-f):C(a.check,n,f,t.next_out-f)),t.data_type=a.bits+(a.last?64:0)+(a.mode===Se?128:0)+(a.mode===Oe||a.mode===Te?256:0),(0===_&&0===f||e===be)&&x===ke&&(x=Ee),x},inflateEnd:t=>{if(Ce(t))return xe;let e=t.state;return e.window&&(e.window=null),t.state=null,ke},inflateGetHeader:(t,e)=>{if(Ce(t))return xe;const a=t.state;return 0==(2&a.wrap)?xe:(a.head=e,e.done=!1,ke)},inflateSetDictionary:(t,e)=>{const a=e.length;let i,n,s;return Ce(t)?xe:(i=t.state,0!==i.wrap&&i.mode!==Ue?xe:i.mode===Ue&&(n=1,n=C(n,e,a,0),n!==i.check)?ze:(s=We(t,e,a,a),s?(i.mode=16210,Ae):(i.havedict=1,ke)))},inflateInfo:"pako inflate (from Nodeca project)"};var Je=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const Qe=Object.prototype.toString,{Z_NO_FLUSH:Ve,Z_FINISH:$e,Z_OK:ta,Z_STREAM_END:ea,Z_NEED_DICT:aa,Z_STREAM_ERROR:ia,Z_DATA_ERROR:na,Z_MEM_ERROR:sa}=K;function ra(t){this.options=jt({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt,this.strm.avail_out=0;let a=qe.inflateInit2(this.strm,e.windowBits);if(a!==ta)throw new Error(j[a]);if(this.header=new Je,qe.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Gt(e.dictionary):"[object ArrayBuffer]"===Qe.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=qe.inflateSetDictionary(this.strm,e.dictionary),a!==ta)))throw new Error(j[a])}function oa(t,e){const a=new ra(e);if(a.push(t),a.err)throw a.msg||j[a.err];return a.result}ra.prototype.push=function(t,e){const a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?$e:Ve,"[object ArrayBuffer]"===Qe.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=qe.inflate(a,r),s===aa&&n&&(s=qe.inflateSetDictionary(a,n),s===ta?s=qe.inflate(a,r):s===na&&(s=aa));a.avail_in>0&&s===ea&&a.state.wrap>0&&0!==t[a.next_in];)qe.inflateReset(a),s=qe.inflate(a,r);switch(s){case ia:case na:case aa:case sa:return this.onEnd(s),this.ended=!0,!1}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===ea))if("string"===this.options.to){let t=Wt(a.output,a.next_out),e=a.next_out-t,n=Xt(a.output,t);a.next_out=e,a.avail_out=i-e,e&&a.output.set(a.output.subarray(t,t+e),0),this.onData(n)}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==ta||0!==o){if(s===ea)return s=qe.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break}}return!0},ra.prototype.onData=function(t){this.chunks.push(t)},ra.prototype.onEnd=function(t){t===ta&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var la={Inflate:ra,inflate:oa,inflateRaw:function(t,e){return(e=e||{}).raw=!0,oa(t,e)},ungzip:oa,constants:K};const{Deflate:ha,deflate:da,deflateRaw:_a,gzip:fa}=le,{Inflate:ca,inflate:ua,inflateRaw:wa,ungzip:ma}=la;var ba=ha,ga=da,pa=_a,ka=fa,va=ca,ya=ua,xa=wa,za=ma,Aa=K,Ea={Deflate:ba,deflate:ga,deflateRaw:pa,gzip:ka,Inflate:va,inflate:ya,inflateRaw:xa,ungzip:za,constants:Aa};t.Deflate=ba,t.Inflate=va,t.constants=Aa,t.default=Ea,t.deflate=ga,t.deflateRaw=pa,t.gzip=ka,t.inflate=ya,t.inflateRaw=xa,t.ungzip=za,Object.defineProperty(t,"__esModule",{value:!0})}));